首页 > 语言 > JavaScript > 正文

浅谈vuex为什么不建议在action中修改state

2024-05-06 15:43:59
字体:
来源:转载
供稿:网友

背景

在最近的一次需求开发过程中,有再次使用到Vuex,在状态更新这一方面,我始终遵循着官方的“叮嘱”,谨记“一定不要在action中修改state,而是要在mutation中修改”;于是我不禁产生了一个疑问:Vuex为什么要给出这个限制,它是基于什么原因呢?带着这个疑问我查看Vuex的源码,下面请大家跟着我的脚步,来一起揭开这个问题的面纱。

一起阅读源码吧~

1.首先我们可以在src/store.js这个文件的Store类中找到下面这段代码

// ...this.dispatch = function boundDispatch (type, payload) { return dispatch.call(store, type, payload)}this.commit = function boundCommit (type, payload, options) { return commit.call(store, type, payload, options)}// ...

上面是Vuex两个最核心的API:dispatch & commit,它们是分别用来提交action和mutation的

那么既然我们今天的目的是为了“了解为什么不能在action中修改state”,所以我们就先看看mutation是怎样修改state的,然而mutation是通过commit提交的,所以我们先看一下commit的内部实现

commit&mutation

2.commit方法的核心代码大致如下:

commit (_type, _payload, _options) {  // ...  this._withCommit(() => {   entry.forEach(function commitIterator (handler) {    handler(payload)   })  })  // ...}

不难看出,Vuex在commit(提交)某种类型的mutation时,会先用_withCommit包裹一下这些mutation,即作为参数传入_withCommit;那么我们来看看_withCommit的内部实现(ps:这里之所以说”某种类型的mutation“,是因为Vuex的确支持声明多个同名的mutation,不过前提是它们在不同的namespace下;action同理)

3._withCommit方法的代码如下:

_withCommit (fn) {  const committing = this._committing  this._committing = true  fn()  this._committing = committing }

是的,你没有看错,它真的只有4行代码;这里我们注意到有一个标志位_committing,在执行fn前,这个标志位会被置为true,这个点我们先记下,一会儿会用到

4.接下来,我要为大家要介绍的是resetStoreVM这个函数,它的作用是初始化store,它首次被执行是在Store的构造函数中

function resetStoreVM (store, state, hot) { // ... if (store.strict) {  enableStrictMode(store) }// ...}

在这里有一处需要我们注意:resetStoreVM对strict(是否启用严格模式)做了判断,这里假设我们启用严格模式,那么就会执行enableStrictMode这个函数,下面继续来看看它的内部实现

function enableStrictMode (store) { store._vm.$watch(function () { return this._data.$$state }, () => {  if (process.env.NODE_ENV !== 'production') {   assert(store._committing, `do not mutate vuex store state outside mutation handlers.`)  } }, { deep: true, sync: true })}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选