Vue 错误消息:不要在突变处理程序之外更改 vuex 存储



我查看了文档,并得到了几个Vue项目顺利运行Vuex,但这个错误令人困惑。

状态.js

return {
articles: [],
currentArticle: null,
}

突变.js

addArticles(state, articles) {
state.articles.push(...articles);
}

在我的 Vue 组件中提交的函数:

async created() {
const recentArticles = [];
const querySnapshot = await this.$firestore.collection('fl_content').limit(5).get();
querySnapshot.forEach(doc => {
recentArticles.push({id: doc.id, ...doc.data()});
});
this.$store.commit('articles/addArticles', recentArticles);
}

我还尝试复制数组进行操作,但这没有帮助。

错误:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."
vue.runtime.esm.js?2b0e:1888 Error: [vuex] do not mutate vuex store state outside mutation handlers.
(found in <Root>)

这是因为,当你第一次提交时

this.$store.commit('articles/addArticles', recentArticles);

最近文章的浅层副本保存在 Vuex 中。 现在,如果您在组件中更改最近文章,它将生成此错误。

所以解决方案是在提交时创建最近文章的深层副本

this.$store.commit('articles/addArticles', [...recentArticles]);

虽然有很多方法可以创建深拷贝,但这是最简单的方法。

最新更新