Skip to content

mobx-miniprogram 状态管理

仓库:
mobx-miniprogram:https://github.com/wechat-miniprogram/mobx-miniprogram
mobx-miniprogram-bindings:https://github.com/wechat-miniprogram/mobx-miniprogram-bindings
关联清单:https://github.com/justjavac/awesome-wechat-weapp

MobX 是响应式状态管理模型。mobx-miniprogram 将其引入微信小程序环境,配合 mobx-miniprogram-bindings 可将 Store 与页面/组件进行双向绑定,简化 setData 与手动同步。

🎯 文章目标

  • 初始化 mobx-miniprogram 并创建 Store
  • 使用 createStoreBindings 在页面/组件绑定状态与动作
  • 组织全局与局部状态,拆分模块
  • 处理异步、持久化与调试

📦 安装

bash
npm i mobx-miniprogram mobx-miniprogram-bindings -S
# 微信开发者工具:工具 -> 构建 npm

🧱 创建 Store

js
// stores/counter.js
import { observable, action } from 'mobx-miniprogram'

export const counterStore = observable({
  n: 0,

  inc: action(function () { this.n++ }),
  dec: action(function () { this.n-- }),

  // 支持异步
  asyncInc: action(async function () {
    await new Promise(r => setTimeout(r, 300))
    this.n++
  })
})

可建立 index 聚合导出:

js
// stores/index.js
export { counterStore } from './counter'

🔗 页面绑定

js
// pages/index/index.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { counterStore } from '../../stores/counter'

Page({
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store: counterStore,
      fields: ['n'],
      actions: ['inc', 'dec', 'asyncInc']
    })
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  }
})
xml
<!-- pages/index/index.wxml -->
<view class="container">
  <text>计数:\{\{n\}\}</text>
  <button bindtap="inc">+1</button>
  <button bindtap="dec">-1</button>
  <button bindtap="asyncInc">异步 +1</button>
</view>

🧩 组件绑定

js
// components/counter/index.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { counterStore } from '../../stores/counter'

Component({
  lifetimes: {
    attached() {
      this.storeBindings = createStoreBindings(this, {
        store: counterStore,
        fields: { value: 'n' },
        actions: ['inc', 'dec']
      })
    },
    detached() { this.storeBindings.destroyStoreBindings() }
  }
})
wxml
<!-- components/counter/index.wxml -->
<view class="counter">
  <text>\{\{value\}\}</text>
  <button bindtap="inc">+1</button>
  <button bindtap="dec">-1</button>
</view>

🏗️ 工程实践

  • Store 分层:domain store(业务域)+ ui store(视图状态)
  • 持久化:关键字段写入 Storage;启动时 hydrate
  • 异步与错误:action 中捕获异常,统一 toast/埋点
  • 性能:避免绑定过多 fields;对大对象拆粒度

🧪 常见问题

  • “未构建 npm”:删除 miniprogram_npm 重新构建
  • setData 冲突:使用 bindings 后避免手动 setData 同名字段
  • 循环依赖:拆分 store 模块,使用依赖注入或延迟引用

✅ 适用场景

  • 中大型项目的全局/跨页面状态
  • 需要响应式、可测试的状态模型
  • 与请求层/缓存层配合,构建可维护的数据流

🔗 参考

📊 总结

mobx-miniprogram 提供轻量的响应式状态体验。结合 bindings 与合理的模块化,可以在小程序中实现清晰的数据流与稳定的工程形态。