2016-07-14 96 views
5

我試圖創建一個listenAuth功能手錶在火力onAuthStateChanged」通知vuex店當用戶有登錄或退出。據我所知,我只使用突變處理程序修改state.authData,除非我失去了一些東西?Vuex&VueJS(不要變異突變處理之外vuex商店狀態)

,我發現了錯誤:

[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: {} 
} 
+0

您可能需要升級到Vuex 2.0 –

回答

3

同樣的問題掙扎後,我發現,當我們試圖在auth /用戶數據存儲在Vuex狀態的錯誤僅發生。

下更改...

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

...到...

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

將解決你的情況。

+1

請改用'state.authData = Object.assign({},authData)'。看看下面的答案。 –

7

我也遇到過這個問題。我的店:

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 of payload.items instead.

對於狀態對象,使用方法:

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

並且不使用JSON.parse(JSON.stringify(someObj)),因爲它是慢得多。