1. 使用
# 全局安装 npm install -g create-react-app # 构建一个my-app的项目 npx create-react-app my-app cd my-app # 启动编译当前的React项目,并自动打开 http://localhost:3000/ npm start
2. 安装 mobx
yarn add mobx mobx-react
3. 由于 react 不支持最新的装饰器写法 需要如下操作
Support for the experimental syntax 'decorators-legacy' isn't currently enabled
npm install customize-cra react-app-rewired @babel/plugin-proposal-decorators --save
项目根目录新建config-overrides.js文件加入以下代码:
const { override, addDecoratorsLegacy } = require('customize-cra');
module.exports = override(
addDecoratorsLegacy()
);
修改package.json文件如下:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
4.

5. 新建 store 目录
6. 新建 模块文件

store
-- aboutStore.js
-- index.js
-- newsStore.js
ababoutStore.js
import { action, observable , makeAutoObservable} from 'mobx';
class AboutStore {
constructor(){
makeAutoObservable(this)
}
@observable
abouts = '123'
@observable
numbers = 1
@action
setAbout = (abouts) => {
this.abouts = abouts
}
@action
setNumbers = () => {
this.numbers++
}
}
const aboutStore = new AboutStore();
export default aboutStore;
newsStore.js
import { action, observable , makeAutoObservable} from 'mobx';
class NewsStore {
constructor(){
makeAutoObservable(this)
}
@observable
news = '重要新闻'
@action
setNews = (news) => {
this.news = news
}
}
const newsStore = new NewsStore();
export default newsStore;

index.js
/* eslint-disable import/no-anonymous-default-export */
import aboutStore from './aboutStore'
import newsStore from './newsStore'
export default {
aboutStore,
newsStore
}
入口 index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from "mobx-react"
import stores from './store'
// import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<Provider {...stores}>
<App />
</Provider>,
document.getElementById('root')
);
app.js
import './App.css';
import { Observer,observer,useLocalObservable} from 'mobx-react';
import store from './store'
const App = () => {
const localStore = useLocalObservable(() => store);
const { aboutStore,newsStore} = localStore
return <Observer>{
() => <div>
<div>{aboutStore.abouts}</div>
<p style={{cursor:'pointer'}} onClick={ () => aboutStore.setAbout('哈哈哈')}>改变about</p>
<p>{aboutStore.numbers}</p>
<button onClick = { aboutStore.setNumbers }>add</button>
<hr/>
<h2>{newsStore.news}</h2>
<button onClick={() => newsStore.setNews('非重要新闻') }>改变标题</button>
</div>
}</Observer>
}
export default observer(App);

