转载自:https://www.jianshu.com/p/66dd328726d7git
异步actiongithub
class Store { @observable githubProjects = [] @observable state = "pending" // "pending" / "done" / "error" @action fetchProjects() { this.githubProjects = [] this.state = "pending" fetchGithubProjectsSomehow().then( // 内联建立的动做 action("fetchSuccess", projects => { const filteredProjects = somePreprocessing(projects) this.githubProjects = filteredProjects this.state = "done" }), // 内联建立的动做 action("fetchError", error => { this.state = "error" }) ) } }
// 第二种写法promise
class Store { @observable githubProjects = [] @observable state = "pending" // "pending" / "done" / "error" @action fetchProjects() { this.githubProjects = [] this.state = "pending" fetchGithubProjectsSomehow().then( projects => { const filteredProjects = somePreprocessing(projects) // 将修改放入一个异步动做中 runInAction(() => { this.githubProjects = filteredProjects this.state = "done" }) }, error => { runInAction(() => { this.state = "error" }) } ) } }
第二种方案,用async function来处理业务,那么咱们能够使用runInAction这个API来解决以前的问题 。异步
import {observable, action, useStrict, runInAction} from 'mobx'; useStrict(true); class Store { @observable name = ''; @action load = async () => { const data = await getData(); // await以后,修改状态须要动做 runInAction(() => { this.name = data.name; }); } }
flow 只能做为函数使用,不能做为装饰器使用。 flow 能够很好的与 MobX 开发者工具集成,因此很容易追踪 async 函数的过程。async
mobx.configure({ enforceActions: true }) class Store { @observable githubProjects = [] @observable state = "pending" fetchProjects = flow(function * () { // <- 注意*号,这是生成器函数! this.githubProjects = [] this.state = "pending" try { const projects = yield fetchGithubProjectsSomehow() // 用 yield 代替 await const filteredProjects = somePreprocessing(projects) // 异步代码块会被自动包装成动做并修改状态 this.state = "done" this.githubProjects = filteredProjects } catch (error) { this.state = "error" } }) }