状态变量触发突变错误

State Variable triggers mutation error

我的商店模块中有以下伪代码

const state = {
  users: []
}

const actions = {
 addUsers: async ({commit, state}, payload) => {
   let users = state.users // <-- problem
   // fetching new users
   for(let i of newUsersThatGotFetched) {
     users.push('user1') // <-- really slow
   }
   commit('setUsers',users)
 }
}

const mutations = {
  setUsers: (state, { users }) => {
    Vue.set(state, 'users', users)
   }
  }

现在 - 当我 运行 这段代码时,我得到以下错误 Error: [vuex] Do not mutate vuex store state outside mutation handlers

当我将严格模式设置为 false 时 - 错误消失了 - 但处理时间真的非常慢 - 好像错误仍然发生但没有显示。

问题似乎出在我评论 // <-- problem 的地方,因为在我将该行更改为

之后
 let users = []

一切 运行 都完美无缺,但我不能拥有它,因为我需要 state.users

的数据

问题是:users.push('user1'),这是改变状态的行。

从操作中删除任何会改变状态(写入或更改状态)的内容,并将其移动到突变中。

 addUsers: async ({ commit }, payload) => {
   // fetching new users
   commit('setUsers', newUsersThatGotFetched)
 }

然后在突变中添加新用户。

const mutations = {
  setUsers: (state, users) => {
    state.users.concat(users);
    // or if you have custom logic
    users.forEach(user => {
      if (whatever) state.users.push(user)
    });
  }
}

慢的原因与Strict mode

有关

Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost.

如果你想加速突变,你可以在一个新数组上进行更改,该数组将替换准备就绪状态中的数组。

const mutations = {
  setUsers: (state, newUsers) => {
    state.users = newUsers.reduce((users, user) => {
      if (whatever) users.push(user);
      return users;
    }, state.users.slice()); // here, we start with a copy of the array
  }
}