Skip to content
目录

MobX 核心架构概述

MobX 实现 透明响应式(TFRP):把 state 标成 observable,时自动收集依赖,时自动通知 computed / reaction / observer 组件更新。

Anything that can be derived from the application state, should be. Automatically.


1. 三要素

要素角色API 举例
State可观察数据observable / makeAutoObservable
Action修改 state 的事务边界action / runInAction
Derivation从 state 推出computed(值)、reaction/autorun(副作用)

2. 类层次(读源码用)

text
Atom / ObservableValue / ObservableObject / Array / Map / Set
        ↑ reportObserved / reportChanged
Derivation ← ComputedValue, Reaction

不必记全类名;抓住 observable ↔ derivation 多对多 即可。


3. 依赖状态机(概念)

Derivation 对依赖有 UP_TO_DATE / POSSIBLY_STALE / STALE 等状态,用于懒传播、少算(见 03-状态传播)。


4. 数据流

mermaid
flowchart LR
  A[action 改 observable] --> B[notify observers]
  B --> C[computed 重算]
  B --> D[reaction 跑副作用]
  B --> E[observer 组件重渲染]

5. 与 Redux 选型

MobXRedux
可变 + 自动依赖不可变 + dispatch
少样板多纪律
适合快速迭代 UI适合强流程与审计

6. 包与 React


7. 总结

MobX 卖的是 自动依赖图;写对 action 边界、拆细 observer,比背 Atom 源码更重要。

MIT License.