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

时间:2020-04-10 16:19:38

标签: javascript vue.js vuejs2 vuex nuxt.js

我正在从主布局调用存储操作(nuxt.js default.vue) 然后,我在突变导出中调用状态突变。为什么会出现此错误?

控制台错误:http://prntscr.com/rwvfjf

代码:

default.vue

created () {
  this.$store.dispatch("update_user");
  ...
}

商店(store / index.js)

export const state = {
  ...
  state: null, 
}

export const actions {
  ...
  update_user({commit}) {commit("update_user")}
}

export const mutations = {
  async update_user(state) {
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    state.user = user;
  },
}

1 个答案:

答案 0 :(得分:1)

来自the docs

突变必须同步

要记住的一个重要规则是,变异处理函数必须是同步的

您似乎已将它们颠倒了。将您的动作和突变重组为:

动作

export const actions = {  // <-- was missing an equals
  ...
  async update_user({ state, commit }) { // <-- state and commit needed
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    commit("update_user", user); // <-- Passing the user data to the mutation
  }
}

突变

export const mutations = {
  update_user(state, user) {
    state.user = user;
  },
}

还请注意,异步操作将返回数据,然后将数据传递给设置为状态的突变。一旦解决,您this.$axios可能也会出错。如果是这样,请确保要导入它:

import axios from 'axios';

并像这样使用它:

if (axios.defaults.headers.common["authorization"] == undefined) {
  axios.defaults.headers.common["authorization"] = state.token
}