VUEX-action可以修改state吗
首先回顾下vuex,官网图如下
- Vuex的store中的状态的唯一方法是提交mutation(mutation类似于事件且必须是同步函数)
- action提交的是mutation,而不是直接变更状态且可以包含任意异步操作(Action通过store.dispatch方法触发)
一幅图看清只能通过mutation修改state的原因
commit函数源码如下
commit(_type,_payload,_options){
//checkobject-stylecommit
const{
type,
payload,
options
}=unifyObjectStyle(_type,_payload,_options)
constmutation={type,payload}
constentry=this._mutations[type]
if(!entry){
if(process.env.NODE_ENV!=='production'){
console.error(`[vuex]unknownmutationtype:${type}`)
}
return
}
//用来修改state
this._withCommit(()=>{
entry.forEach(functioncommitIterator(handler){
handler(payload)
})
})
this._subscribers.forEach(sub=>sub(mutation,this.state))
if(
process.env.NODE_ENV!=='production'&&
options&&options.silent
){
console.warn(
`[vuex]mutationtype:${type}.Silentoptionhasbeenremoved.`+
'Usethefilterfunctionalityinthevue-devtools'
)
}
}
this._withCommit来修改state,其源代码如下
_withCommit(fn){
constcommitting=this._committing
this._committing=true
fn()
this._committing=committing
}
其中_withCommit函数的参数fn是修改state的函数,在执行fn函数前,将this._committing置为true,理由是在源代码的251行resetStoreVM函数中判断严格模式的代码,如下:
if(store.strict){
enableStrictMode(store)
}
当vuex设置为严格模式,执行enableStrictMode函数,源码如下:
functionenableStrictMode(store){
//$watch函数来观察state的变化
store._vm.$watch(function(){returnthis._data.$$state},()=>{
//tate变化时,调用assert函数
if(process.env.NODE_ENV!=='production'){
//判断store._committing
assert(store._committing,`donotmutatevuexstorestateoutsidemutationhandlers.`)
}
},{deep:true,sync:true})
}
当store._committing(this._committing)不为true,就会报出异常。
所以,当不是触发mutation来修改state,就不会执行commit函数,也不会执行_withcommit函数,this._committing=true不会执行,当执行enableStrictMode时,会执行assert函数,这时store._committing为false,就会报出异常。
回归标题action可以修改state吗
不开启严格模式的情况下可以,但是不提倡。
综上所述,经测试得知可以修改并修改成功,但是严格模式下控制台会抛异常且action是异步的,不方便DevTool调试
结语
我们开发要严格按照官方文档开发,避免不必要的错误产生。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。