在 MobX 状态树(MST)中执行异步操作的推荐方法是使用
flow
,它采用生成器函数作为第一个参数,其中每个 Promise 都应该被生成。
yield
表达式在 TypeScript中属于
any
类型,但是有没有办法在 MST 中自动键入 Yield 表达式?
示例
import { flow, types } from "mobx-state-tree";
type Stuff = { id: string; name: string };
function fetchStuff(): Promise<Stuff[]> {
return new Promise((resolve) => {
resolve([
{ id: "1", name: "foo" },
{ id: "2", name: "bar" }
]);
});
}
const Thing = types.model({
id: types.identifier,
name: types.string
});
const ThingStore = types
.model({
things: types.array(Thing)
})
.actions((self) => ({
fetchThings: flow(function* () {
// "stuff" is of type "any"!
const stuff = yield fetchStuff();
self.things.replace(stuff);
})
}));
toGenerator 可用于将 Promise 转换为生成该 Promise 的生成器。这与
yield*
而不是 yield
(可以通过在 TypeScript 编译器选项中将 downlevelIteration
设置为
true
来使用)一起使用,从而保留 Promise 返回类型。
import { flow, types, toGenerator } from "mobx-state-tree";
type Stuff = { id: string; name: string };
function fetchStuff(): Promise<Stuff[]> {
return new Promise((resolve) => {
resolve([
{ id: "1", name: "foo" },
{ id: "2", name: "bar" }
]);
});
}
const Thing = types.model({
id: types.identifier,
name: types.string
});
const ThingStore = types
.model({
things: types.array(Thing)
})
.actions((self) => ({
fetchThings: flow(function* () {
// "stuff" is now of type "Stuff[]"!
const stuff = yield* toGenerator(fetchStuff());
self.things.replace(stuff);
})
}));
也可以使用 typescript 或 babel 转换插件稍后进行翻译:
在原生 Typescript 中,遗憾的是(目前)还无法描述
yield
的返回类型 - 请参阅本期中的详细信息