安装 Mobx 及所需相关 babel 依赖

  1. Mobx

    script
    npm insatall mobx --save npm insatall mobx-react --save
  2. babel

    script
    npm install babel-plugin-transform-decorators-legacy --save-dev npm install @babel/plugin-proposal-decorators --save-dev # 或者 npm install @babel/plugin-proposal-decorators babel-plugin-transform-decorators-legacy --save-dev
  3. 配置 babel

.babelrc 或者 babel.config.js 或者在 package.json

script
plugins:[ ["@babel/plugin-proposal-decorators", {"legacy":true}], ["@babel/plugin-proposal-class-properties", {"loose":true}] ]
  1. 配置 mobx,多 store 组合

文件结构

project
│   app.js  
└───src
│   │
│   └───stores
│       │   todo.js
│       │   index.js
│       │   ...
│   └───pages
│       │   todoPage.js
│       │   ...
│   

4.1 src/stores/todo.js

import {
  observable,
  action,
  computed,
} from 'mobx';


export class TodoStore {
  @observable name = '555';
  
  // 不接受任何参
  @computed get getName() {
    return this.name;
  }
  
  // @autorun( () => {
  // })
  
  @action.bound setName(name) {
    console.log(this.name, name);
  }
  
  // 或者
  @action
  setName = (name) => {
    console.log(this.name, name);
  }
}


export const STORE_TODO = 'todoStore';

export default TodoStore;

4.2 src/stores/index.js

import TodoStore, { STORE_TODO, TodoType } from "./todo";

class RootStore {
  [STORE_TODO]: TodoType
  constructor() {
    this[STORE_TODO] = new TodoStore();
  }
}

export default new RootStore();

4.4 /app.js

+ import RootStore from './src/store/index';
+ import { Provider } from 'mobx-react';

const App: () => React$Node = () => {
  return (
+    <Provider {...RootStore}>
        .....
+    </Provider>
  );
};