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 选型
| MobX | Redux |
|---|---|
| 可变 + 自动依赖 | 不可变 + dispatch |
| 少样板 | 多纪律 |
| 适合快速迭代 UI | 适合强流程与审计 |
6. 包与 React
7. 总结
MobX 卖的是 自动依赖图;写对 action 边界、拆细 observer,比背 Atom 源码更重要。