---
type: snippet
tags: ['mobx', 'async', 'action']
status: release
ctime: 2022-10-16
mtime: 2024-03-22
---

MobX 비동기 action 처리 - `action`은 현재 스택에만 적용됨. await/then 이후 상태 변경은 별도 action 필요.

```javascript
// ❌ 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"
  }
})
```

> [!TIP]
> `flow`는 async/await와 동일하게 작동하면서 수동 action 래핑 불필요. 취소도 가능 (`cancel()`).

- [MobX Actions 문서](https://github.com/mobxjs/mobx/blob/mobx4and5/docs/best/actions.md)
