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

前端之家收集整理的这篇文章主要介绍了javascript – Vuex和VueJS(不要在突变处理程序之外改变vuex存储状态)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个listenAuth函数,该函数在firebase中监视“onAuthStateChanged”,以便在用户登录或注销时通知vuex存储.据我所知,我只是使用变异处理程序修改state.authData,除非我遗漏了什么?

我收到错误

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

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

  1. <script>
  2. // import Navigation from './components/Navigation'
  3. import * as actions from './vuex/actions'
  4. import store from './vuex/store'
  5. import firebase from 'firebase/app'
  6.  
  7. export default {
  8. store,ready: function () {
  9. this.listenAuth()
  10. },vuex: {
  11. actions,getters: {
  12. authData: state => state.authData,user: state => state.user
  13. }
  14. },components: {
  15. // Navigation
  16. },watch: {
  17. authData (val) {
  18. if (!val) {
  19. this.redirectLogin
  20. this.$route.router.go('/login')
  21. }
  22. }
  23. },methods: {
  24. listenAuth: function () {
  25. firebase.auth().onAuthStateChanged((authData) => {
  26. this.changeAuth(authData)
  27. })
  28. }
  29. }
  30. }
  31. </script>

这是我的动作(changeAuth)功能

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

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

  1. const mutations = {
  2. AUTH_CHANGED (state,authData) {
  3. state.authData = authData
  4. }
  5. }
  6.  
  7. const state = {
  8. authData: {}
  9. }

解决方法

我也遇到过这个问题.我的商店:
  1. state: {
  2. items: []
  3. },mutations: {
  4. SetItems (state,payload) {
  5. // Warning
  6. state.items = payload.items
  7. }
  8. },actions: {
  9. FetchItems ({commit,state},payload) {
  10. api.getItemsData(payload.sheetID)
  11. .then(items => commit('SetItems',{items}))
  12. }
  13. }

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

  1. 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.

对于状态对象,请使用:

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

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

猜你在找的JavaScript相关文章