Vuex 和 VueJS(不要在变异处理程序之外改变 vuex 存储状态)

新手上路,请多包涵

我正在尝试创建一个 listenAuth 函数,该函数在 firebase 中监视“ onAuthStateChanged ”,以在用户登录或注销时通知 vuex 存储。据我所知,我只是使用变异处理程序修改 state.authData,除非我遗漏了什么?

我收到错误:

 [vuex] Do not mutate vuex store state outside mutation handlers.

这是我的 App.vue javascript(来自我的组件)

 <script>
// import Navigation from './components/Navigation'
import * as actions from './vuex/actions'
import store from './vuex/store'
import firebase from 'firebase/app'

export default {
  store,
  ready: function () {
    this.listenAuth()
  },
  vuex: {
    actions,
    getters: {
      authData: state => state.authData,
      user: state => state.user
    }
  },
  components: {
    // Navigation
  },
  watch: {
    authData (val) {
      if (!val) {
        this.redirectLogin
        this.$route.router.go('/login')
      }
    }
  },
  methods: {
    listenAuth: function () {
      firebase.auth().onAuthStateChanged((authData) => {
        this.changeAuth(authData)
      })
    }
  }
}
</script>

这是我的操作 (changeAuth) 函数

export const changeAuth = ({ dispatch, state }, authData) => {
  dispatch(types.AUTH_CHANGED, authData)
}

这是我的商店(重要的部分)

 const mutations = {
  AUTH_CHANGED (state, authData) {
    state.authData = authData
  }
}

const state = {
  authData: {}
}

原文由 Jayson H 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
1 个回答

我也遇到了这个问题。我的店铺:

   state: {
    items: []
  },
  mutations: {
    SetItems (state, payload) {
      // Warning
      state.items = payload.items
    }
  },
  actions: {
    FetchItems ({commit, state}, payload) {
      api.getItemsData(payload.sheetID)
        .then(items => commit('SetItems', {items}))
    }
  }

通过将 state.items = payload.items 替换为:

 state.items = payload.items.slice()

原因是数组在 Javascript 中存储为引用,并且 payload.items 很可能在 Vuex 之外被更改。所以我们应该只使用 payload.items 的新副本。

对于状态对象,使用:

 state.someObj = Object.assign({}, payload.someObj)

并且不要使用 JSON.parse(JSON.stringify(someObj)) 因为它要慢得多。

原文由 KF Lin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题