Vuex - “不要在变异处理程序之外改变 vuex 存储状态”

taz*_*boy 6 vuex vuejs2 google-cloud-firestore

我正在尝试从 Firestore 初始化我的 Vuex 商店。最后一行代码context.commit('SET_ACTIVITIES', acts)是产生错误的原因。我不认为我在直接改变状态,因为我正在使用一个动作。我可能会错过什么?

这是我的 Vuex 商店:

export default new Vuex.Store({
  strict: true,
  state: {
    activities: []
  },
  mutations: {
    SET_ACTIVITIES: (state, activities) => {
      state.activities = activities
    },
  },

  actions: {
    fetchActivities: context => {
      let acts = []
      let ref = db.collection('activities')
      ref.onSnapshot(snapshot => {
        snapshot.docChanges().forEach(change => {
          if(change.type == 'added') {
            acts.push({
              id: change.doc.id,
              name: change.doc.data().name,
              day: change.doc.data().day
            })
          }
        })
      })
      context.commit('SET_ACTIVITIES', acts)
    }
  }
Run Code Online (Sandbox Code Playgroud)

此外,它给我的错误等于 Firestore 中的项目数。如果我只做一次提交,为什么会这样做?

安慰:

[Vue 警告]:观察者回调错误“function () { return this._data.$$state }”:“错误:[vuex] 不要在变异处理程序之外改变 vuex 存储状态。”

Error: [vuex] do not mutate vuex store state outside mutation handlers.
    at assert (vuex.esm.js?2f62:87)
    at Vue.store._vm.$watch.deep (vuex.esm.js?2f62:763)
    at Watcher.run (vue.runtime.esm.js?2b0e:4562)
    at Watcher.update (vue.runtime.esm.js?2b0e:4536)
    at Dep.notify (vue.runtime.esm.js?2b0e:730)
    at Array.mutator (vue.runtime.esm.js?2b0e:882)
    at eval (store.js?c0d6:36)
    at eval (index.cjs.js?e89a:21411)
    at eval (index.cjs.js?e89a:4904)
    at LLRBNode.inorderTraversal (index.cjs.js?e89a:1899)
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 9

您遇到了对象引用和异步方法的问题。

CollectionReference#onSnapshot()是异步的,在QuerySnapshot事件上触发快照侦听器/观察器。

基本上,在您的代码中发生的情况是,您在突变中将空数组分配actsstate.activities(相同的对象引用),然后在稍后的快照事件处理程序中直接将元素推入其中。

一个快速的解决方案是在onSnapshot观察者中提交突变

fetchActivities: context => {
  let ref = db.collection('activities')
  ref.onSnapshot(snapshot => {
    let acts = []
    snapshot.docChanges().forEach(change => {
      if(change.type == 'added') {
        acts.push({
          id: change.doc.id,
          name: change.doc.data().name,
          day: change.doc.data().day
        })
      }
    })
    context.commit('SET_ACTIVITIES', acts)
  })
}
Run Code Online (Sandbox Code Playgroud)

如果您只想对集合数据进行初始提取,请CollectionReference#get()改用。鉴于它返回一个承诺,您可以使用它来使您的操作可组合

async fetchActivities ({ commit }) {
  let snapshot = await db.collection('activities').get()
  let acts = snapshot.docChanges().filter(({ type }) => type === 'added')
      .map(({ doc }) => ({
        id: doc.id,
        name: doc.data().name,
        day: doc.data().day
      }))
  commit('SET_ACTIVITIES', acts)
}
Run Code Online (Sandbox Code Playgroud)