flow this 类型提示
Published on February 22, 2023Updated on March 23, 2024
Loading content...
Appromal Admin 用的mobx进行状态管理
Mobx 官网推荐在异步场景下使用 flow 进行包装,进行状态更改
https://mobx.js.org/actions.html#using-flow-instead-of-async--await-
flow
, like action
, can be used to wrap functions directly. The above example could also have been written as follows:
TypeScriptimport { flow } from "mobx" class Store { githubProjects = [] state = "pending" fetchProjects = flow(function* (this: Store) { this.githubProjects = [] this.state = "pending" try { // yield instead of await. const projects = yield fetchGithubProjectsSomehow() const filteredProjects = somePreprocessing(projects) this.state = "done" this.githubProjects = filteredProjects } catch (error) { this.state = "error" } }) } const store = new Store() const projects = await store.fetchProjects()
The upside is that we don't need flowResult
anymore, the downside is that this
needs to be typed to make sure its type is inferred correctly.
当时官网似乎还没有代码,因此我的写法是下面这样的
当使用上图的写法来写的时候,会丢失类型提示
https://github.com/mobxjs/mobx/issues/1769#issuecomment-452703686
https://www.logicbig.com/tutorials/misc/typescript/function-this-parameter.html
从这个来看,是个TS的行为,不过没能寻找到出处