Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] vuex怎么知道state是通过mutation修改还是外部直接修改的? #393

Open
haizhilin2013 opened this issue Jun 20, 2019 · 7 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] vuex怎么知道state是通过mutation修改还是外部直接修改的?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@wenyejie
Copy link

不知道哟, mark一下

@logicool
Copy link

logicool commented Jul 1, 2019

通过$watch监听mutation的commit函数中_committing是否为true

@flyfox11
Copy link

这道题感觉有点问题,在vuex严格模式下,是不让外部直接修改state的

@WenJieLi1998
Copy link

修改state数据,只有mutation这唯一路径

@lt846786463
Copy link

不通过mutation直接修改state浏览器会报错

@Drikold
Copy link

Drikold commented Jul 25, 2021

默认严格模式下:Vuex 中修改 state 的唯一渠道就是执行 commit('xx', payload) 方法,其底层通过执行 this._withCommit(fn) 设置_committing 标志变量为 true,然后才能修改 state,修改完毕还需要还原_committing 变量。外部修改虽然能够直接修改 state,但是并没有修改_committing 标志位,所以只要 watch 一下 state,state change 时判断是否_committing 值为 true,即可判断修改的合法性。
跳转链接:Vuex 如何区分 State 是外部直接修改

@rookiewp
Copy link

rookiewp commented Mar 1, 2022

严格模式下:strict = true

vuex源码:
function enableStrictMode (store) {
watch(() => store._state.data, () => {
if (DEV) {
assert(store._committing, do not mutate vuex store state outside mutation handlers.)
}
}, { deep: true, flush: 'sync' })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

8 participants