我正在尝试创建一个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: {} }
解决方法
我也遇到过这个问题.我的商店:
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()
The reason is that arrays are stored as references in Javascript and
payload.items
is likely to be changed outside Vuex. So we should
just use a fresh copy ofpayload.items
instead.
对于状态对象,请使用:
state.someObj = Object.assign({},payload.someObj)
并且不要使用JSON.parse(JSON.stringify(someObj)),因为它要慢得多.