# makeAutoObservable 详解
makeAutoObservable(target, overrides?, options?)
- target:将目标对象中的属性和方法设置为 Observable State 和 Action
- overrides:覆盖默认设置,将- target对象中的某些属性或方法设置为普通属性- 因为并不是所有的属性或方法都需要转化
- overrides对象中的- key是需要覆盖的属性或方法的名称,- value为- false的会被设置成普通属性
 
- options:配置对象
| // 将 reset 方法设置为普通属性,再通过 reset 方法修改状态 MobX 会发出警告(Warning) | |
| constructor() { | |
| makeAutoObservable(this, { reset: false }) | |
| } | |
| 1234 | |
| //autoBind:使 Action 方法始终拥有正确的 this 指向 | |
| //--------- 定义 store 的 class --------- | |
| constructor() { | |
| makeAutoObservable(this, {}, {autoBind: true}) | |
| } | |
| reset() { | |
| console.log(this); | |
| this.count = 0 | |
| } | |
| //--------- 组件中调用方法 --------- | |
| // 正确 this 指向 | |
| <button onClick={() => counterStore.reset()}>重置</button> | |
| // 错误 this 指向 | |
| //   this 指向 undefined | |
| //   开启了 autoBind 后 this 会指向 Store 实例对象 | |
| <button onClick={counterStore.reset}>重置</button> | 
# 状态变化更新视图的必要条件
总结一下状态变化更新视图的必要条件:
- 状态需要被标记为 Observer State
- 更改状态的方法需要被标记为 Action
- 组件视图必须通过 observer(mobx-react-lite 提供) 方法包裹
# makeObservable 手动转化
makeAutoObservable 方法会自动转化 target 对象的属性和方法。
MobX 还提供了 makeObservable 方法,可以手动转化指定的属性或方法。
makeAutoObservable(target, annotations?, options?)
- target:指定要转化的目标实例对象
- annotations:注解对象- key:指定要转化的属性或方法
- value:annotation(注解,从 mobx 引入的方法),指定要转换成什么,例如:- observable:Observable State
- action:Action
 
 
| import { makeObservable, observable, action } from "mobx" | |
| class CounterStore { | |
|   // 数值状态 | |
| count = 10 | |
| constructor() { | |
|     // 将参数对象的属性设置为 Observable State | |
|     // 将参数对象的方法设置为 Action | |
| makeObservable(this, { | |
| count: observable, | |
| increment: action, | |
|       reset: action | |
| }) | |
|   } | |
|   // 使数值 + 1 | |
| increment() { | |
| this.count += 1 | |
|   } | |
|   // 重置数值状态 | |
| reset() { | |
| this.count = 0 | |
|   } | |
| } | |
| export default CounterStore | 
# 更正 this 指向
使用 makeObservable 手动转化的 action,无法通过 options 配置 autoBind 为 true 更正 this 指向。
需要在指定转化类型的时候使用 action.bound
| makeObservable(this, { | |
|   reset: action | |
| }, { | |
| autoBind: true //reset this 指向未变更 | |
| }) | |
| 12345 | |
| makeObservable(this, { | |
| reset: action.bound //reset this 指向变更 | |
| }) | 
