【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
注:转载请注明出处
越是迷茫、浮躁的时候,保持冷静和耐心,尤为重要

浙公网安备 33010602011771号