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

标签 javascript firebase vue.js firebase-authentication vuex

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

我遇到错误:

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

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

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

对于状态对象,使用:

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

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

关于javascript - Vuex 和 VueJS(不要在变异处理程序之外改变 vuex 存储状态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365075/

相关文章:

javascript - JS fetch,没有得到响应的标题

javascript - 如何在使用 angular-file-upload 上传多个文件时更改标题参数

javascript - Firestore where 子句不满足条件。

javascript - 如何将 Angular 中的日期作为时间戳保存到 Firestore?

javascript - Chrome 扩展程序可以作为网络应用程序代替网站吗?

javascript - jquery 通过 id 选择当前正在播放的音频

ios - 在 Swift 3.0 中访问嵌套的 NSDictionary 值

javascript - 为 v-bind 添加条件?

vue.js - 如何将 "key"指定为必需的 Prop ?

javascript - 我使用数组作为参数,并收到一个观察者