【bug修复】—— [vuex] Do not mutate vuex store state outside mutation handlers.

在使用Vuex  actions中的commit方法提交mutation修改state时,报如下错误:

我的写法是:

export const insertSong = function ({commit, state}, song){
       let playlist = state.playlist //直接修改了state中的数据
       let sequenceList = state.sequenceList //直接修改了state中的数据
       let currentIndex = state.currentIndex
       //记录当前歌曲
       let currentSong = playlist[currentIndex]
       //查找当前列表中是否有待插入的歌曲并返回其索引
       letfpIndex = findIndex(playlist, song)
       //因为是插入歌曲,所以索引+1
       currentIndex++
       //插入这首歌到当前索引位置
       playlist.splice(currentIndex, 0, song)
       //如果已经包含了这首歌
       if(fpIndex > -1) {
           //如果当前插入的序号大于列表中的序号
           if(currentIndex > fpIndex) {
              playlist.splice(fpIndex, 1)
              currentIndex--
           }else{
               playlist.splice(fpIndex+1, 1)
           }
       }

       let currentSIndex = findIndex(sequenceList, currentSong) + 1

       let fsIndex = findIndex(sequenceList, song)

       sequenceList.splice(currentSIndex, 0, song)

       if(fsIndex > -1){
          if(currentSIndex > fsIndex){
             sequenceList.splice(fsIndex, 1)
          }else{
             sequenceList.splice(fsIndex + 1, 1)
          }
       }

       commit(types.SET_PLAYLIST, playlist)
       commit(types.SET_SEQUENCE_LIST, sequenceList)
       commit(types.SET_CURRENT_INDEX, currentIndex)
       commit(types.SET_FULL_SCREEN, true)
       commit(types.SET_PLAYING_STATE, true)
}

报错原因:更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,这是官网原话。

              意思是state中的值必须在回调函数中更改

[types.SET_PLAYLIST](state, list){
       state.playlist = list //回调函数中修改state数据
 }

我在Vuex中开启了严格模式,关于严格模式,Vuex官方文档是这么写的 ↓

开启严格模式,仅需在创建 store 的时候传入 strict: true; 

  • 在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。
  • 这能保证所有的状态变更都能被调试工具跟踪到

通过commit 提交 mutation 的方式来修改 state 时,vue的调试工具能够记录每一次state的变化,这样方便调试。

但是如果是直接修改state,则没有这个记录。

//Vuex 内置日志插件用于一般的调试
import createLogger from 'vuex/dist/logger'

//只在开发环境时启动严格模式
const debug = process.env.NODE_ENV !== 'production'

//工厂方法输出一个单例Vuex.Store模式
export default new Vuex.Store({
    actions,
    getters,
    state,
    mutations,
    strict: debug, //开启严格模式
    plugins: debug ? [createLogger()] : []
})

解决方法:

1.  将state中要修改的数据复制一个副本进行修改,再提交

 let playlist = state.playlist.slice() //副本
 let sequenceList = state.sequenceList.slice() //副本
 let currentIndex = state.currentIndex  //数值不受影响

2.  把严格模式关闭就可以了

注意: 生产环境中必须设置strict:false

 


注:转载请注明出处

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值