Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

Activity

wenyejie

wenyejie commented on Jun 21, 2019

@wenyejie

不知道哟, mark一下

logicool

logicool commented on Jul 1, 2019

@logicool

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

flyfox11

flyfox11 commented on Jul 22, 2019

@flyfox11

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

WenJieLi1998

WenJieLi1998 commented on Apr 18, 2020

@WenJieLi1998

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

lt846786463

lt846786463 commented on Oct 9, 2020

@lt846786463

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

Drikold

Drikold commented on Jul 25, 2021

@Drikold

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

rookiewp

rookiewp commented on Mar 1, 2022

@rookiewp

严格模式下: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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wenyejie@haizhilin2013@Drikold@logicool@flyfox11

        Issue actions

          [vue] vuex怎么知道state是通过mutation修改还是外部直接修改的? · Issue #393 · haizlin/fe-interview