DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 MobX 报错 changing observed observable values outside action 严格模式修复

排查 在 React 应用中开启 MobX enforceActions 严格模式后在异步请求回调或 setTimeout 中直接修改 observable 状态抛出 Error: Since strict-mode is enabled 异常,分析 runInAction 与 action 边界控制。

问题现象

MobX 6 默认将 enforceActions 设置为 "always" 或 "observed",以保障单向数据流与状态可溯源性。当开发者在异步操作(如 await api.getData() 或 setTimeout)完成后,直接对 store 属性执行 this.data = res 时,MobX 运行时坚决拦截并抛出:[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: UserStore@1.status,导致业务逻辑中断。

排查分析

检查报错指向的异步修改代码段

查看 src/stores/UserStore.ts:

class UserStore {
  status = 'idle';
  async fetchStatus() {
    const res = await api.getStatus();
    // 错误示例:await 之后的代码脱离了原来的 action 上下文执行帧
    this.status = res.data; // 抛出 strict-mode 报错
  }
}

检查 MobX 配置入口 configure({ enforceActions: ... })

确认严格模式激活级别;

通过断点追踪 fetchStatus 执行期间当前激活的 MobX 动作环境

确认在 Promise 微任务执行时 isAction 标志位为 false。

触发根因

  1. JavaScript 的 async/await 在 await 恢复后运行在微任务队列中,原函数的 action 作用域已经退栈结束;
  2. 在组件的普通事件回调中直接对 store 的 observable 变量赋值而非调用类方法;
  3. 未在异步回调代码块中使用 runInAction 进行包裹。

解决步骤

在 await 之后的赋值代码中使用 runInAction 包裹

重构 Store 方法:

import { makeAutoObservable, runInAction } from 'mobx';

class UserStore {
  status = 'idle';
  constructor() {
    makeAutoObservable(this);
  }

  async fetchStatus() {
    const res = await api.getStatus();
    runInAction(() => {
      this.status = res.data; // 在独立 action 块中安全赋值
    });
  }
}

使用 MobX 的 flow 搭配 Generator 函数处理异步流程

更符合原生 MobX 哲学的优雅写法:

import { flow } from 'mobx';

fetchStatus = flow(function* (this: UserStore) {
  const res = yield api.getStatus();
  this.status = res.data; // 自动被 flow 包装为 action
});

禁止业务组件直接变更属性

将字段设置为私有或通过 TypeScript 只读修饰符限制。

验证确认

重新在界面触发异步加载:

状态变更在严格模式约束下合法合规流转,无任何控制台拦截警告,状态突变安全受控。