MobX 비동기 action 처리 - action은 현재 스택에만 적용됨. await/then 이후 상태 변경은 별도 action 필요.
// ❌ then 콜백은 action 범위 밖
@action fetchProjects() {
fetchSomething().then(projects => {
this.data = projects // 에러!
})
}
// ✅ 방법 1: runInAction
@action async fetchProjects() {
const data = await fetchSomething()
runInAction(() => {
this.data = data
})
}
// ✅ 방법 2: flow (권장) - await 대신 yield
fetchProjects = flow(function* () {
this.state = "pending"
try {
this.data = yield fetchSomething() // 자동으로 action 래핑
this.state = "done"
} catch (e) {
this.state = "error"
}
})
flow는 async/await와 동일하게 작동하면서 수동 action 래핑 불필요. 취소도 가능 (cancel()).