MobX @flow装饰器生成器函数与TypeScript类型冲突问题求助
MobX @flow装饰器生成器函数与TypeScript类型冲突问题求助
嘿,我来帮你捋捋这个问题!
问题根因
这个报错的核心是MobX的@flow装饰器会自动把你的生成器函数包装成CancellablePromise类型,但你手动给函数指定的返回类型是原生的Generator,这俩类型当然对不上啦。你说其他同类型函数没问题,大概率是那些函数没有显式返回值,或者返回值的类型刚好和MobX的包装逻辑兼容了。
可行的解决方案
给你几个实用的处理方案,挑适合你项目的来用:
- 方案1:去掉手动指定的Generator返回类型
MobX的@flow装饰器本身就会自动推导生成器函数的类型,完全不需要你手动写Generator<...>这种长类型。直接删掉函数的返回类型标注,让TypeScript和MobX自己协调:
@flow *getAllBadgeColors() { try { const { data }: AxiosResponse<GetBadgeColorsResponse> = yield Axios.get(ApiService.GET_COLORS_API, { params: { limit: 1000 }, }); this.badgeColors = data.data; return data.data; } catch (error) { this.error = true; throw error; } }
- 方案2:显式使用MobX的CancellablePromise类型
如果你一定要手动标注返回类型,那就直接用MobX提供的CancellablePromise,这才是@flow装饰器处理后实际返回的类型:
import { CancellablePromise } from "mobx"; @flow *getAllBadgeColors(): CancellablePromise<BadgeColor[]> { try { const { data }: AxiosResponse<GetBadgeColorsResponse> = yield Axios.get(ApiService.GET_COLORS_API, { params: { limit: 1000 }, }); this.badgeColors = data.data; return data.data; } catch (error) { this.error = true; throw error; } }
- 方案3:改用MobX内置的Generator类型
MobX自己定义了适配@flow的Generator类型,你可以导入它来替换原生的Generator类型,这样就能和装饰器的逻辑对齐:
import { Generator } from "mobx"; @flow *getAllBadgeColors(): Generator<Promise<AxiosResponse<GetBadgeColorsResponse>>, BadgeColor[], AxiosResponse<GetBadgeColorsResponse>> { try { const { data }: AxiosResponse<GetBadgeColorsResponse> = yield Axios.get(ApiService.GET_COLORS_API, { params: { limit: 1000 }, }); this.badgeColors = data.data; return data.data; } catch (error) { this.error = true; throw error; } }
小提示
- 日常开发里尽量让MobX自动处理
@flow函数的类型推导,能省不少手动标注的麻烦,也能减少类型冲突 - 顺便检查下你的MobX和TypeScript版本是否匹配,有时候版本不兼容也会冒出这类奇怪的类型报错
内容来源于stack exchange
相关产品推荐
相关产品推荐

