轉載自: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" } }) }