我在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添加角色,但是当我尝试删除角色时它会对我大喊大叫 .
任何人都可以向我解释这种行为吗?当我深深地复制这块状态时,现在不应该与状态分离,不受vuex的影响,并且可变吗?
2 回答
你的代码有几个问题......
在组件中,
data
应该是一个函数您需要初始化
data
中的所有组件属性,否则它们将不会被激活如果要创建状态属性的本地副本,请在
data
中执行此操作考虑到所有这些,试试这个
十年月亮的第一个评论让我得到答案 . 我用JSON.parse / JSON.stringify成功创建了一个可变对象,但是在我的代码中的其他地方,我将该对象提交到商店中的临时存放位置 . 当我后来试图改变我的本地对象时,在商店中有一个对它的引用,导致引发了突变错误 .
我的第一个操作没有导致错误的原因是因为我此时没有将userModel提交到商店 . 一旦userModel提交到商店,很明显,它开始抛出错误 .