代码之家  ›  专栏  ›  技术社区  ›  EmacsVI

vuex-修改状态的本地副本导致变异错误

  •  -1
  • EmacsVI  · 技术社区  · 6 年前

    我在vue应用程序中遇到了一个无法解释的问题。尝试更新状态块的本地副本时出现以下错误。

    错误:[vuex]不要在变异处理程序外部对vuex存储状态进行变异。

    下面是我在代码中所做工作的示例

    import { mapGetters } from 'vuex'
    export default {
        name: 'sampleComponent',
        data() {
            return {
                userModel: null
            }
        },
        mounted() {
            this.userModel = this.user
        },
        computed: {
            ...mapGetters(['getApplicationUsers']),
            user() {
                return JSON.parse(JSON.stringify(this.getApplicationUsers[0]))
            }
        },
        methods: {
            addUserRole() {
                if (!this.userModel.userRoles.includes("newRole")) {
                    this.userModel.userRoles.push("newRole")
                }
            }
            removeUserRole() {
                let index = this.userModel.userRoles.indexOf("newRole");
                if (index > -1) {
                    this.userModel.userRoles.splice(index, 1)
                }
            }
    }
    

    每当调用removeUserRole时,我都会得到变异错误。我可以用adduserrole添加角色,但当我试图删除角色时,它会对我大喊大叫。

    有人能给我解释一下这种行为吗?当我深深地抄袭这篇文章的时候,不应该 userModel 现在与状态分离,没有Vuex的支持,并且是可变的?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Phil    6 年前

    你的代码有几个问题…

    1. 在一个组件中, data 应该是一个函数
    2. 您需要在中初始化所有组件属性 数据 ,否则他们不会做出反应
    3. 如果要创建状态属性的本地副本,请在 数据

    记住这些,试试这个

    data () {
      return {
        objectModel: {...this.$store.getters.getApplicationUsers[0]}
      }
    }
    
        2
  •  0
  •   EmacsVI    6 年前

    十年月亮的第一句话让我找到了答案。我用json.parse/json.stringify成功地创建了一个可变对象,但是在代码的其他地方,我将该对象提交到存储中的一个临时存放位置。后来当我试图对本地对象进行变异时,在存储中有一个对它的引用,这导致了变异错误被抛出。

    我的第一个操作没有导致错误的原因是因为我当时没有将usermodel提交给商店。显然,一旦usermodel被提交到存储,它就开始抛出错误。