![](/img/trans.png)
[英]Chart.js in a Vue page throws error: do not mutate vuex store state outside mutation handlers
[英]Vue Error Message: Do not mutate vuex store outside of mutation handler
我查看了文檔並使用 Vuex 順利運行了幾個 Vue 項目,但是這個錯誤令人困惑。
狀態.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 中保存了最近文章的淺拷貝。 現在,如果您更改組件中的最近文章,則會生成此錯誤。
所以解決方案是在提交時創建recentArticles的Deep copy
this.$store.commit('articles/addArticles', [...recentArticles]);
盡管創建 Deep Copy 的方法有很多,但這是最簡單的一種。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.