【发布时间】:2026-01-31 12:25:02
【问题描述】:
我来自 Redux,开始学习 MST。
我尝试专业地介绍一下Token的刷新逻辑。我已经解释了它应该做什么:
- 客户端向服务器发送请求
- 服务器每 60 秒回复一次代码 401
- 客户端知道是401的时候要刷新token,发送刷新token请求
- 客户端在收到服务器的肯定响应后,是要先重复该动作。
为了整改,我使用 Ignite (React-Native) 中的 Boilerplate:
export const AuthenticationStoreModel = types
.model("AuthenticationStore")
.props({
isAuthenticationed: types.optional(types.boolean, false),
})
.extend(withEnvironment)
.extend(withRootStore)
.actions((self) => ({
setAuthenticated(value: boolean) {
self.isAuthenticationed = value
},
refreshToken: flow(function* () {
const authenticationApi = new AuthenticationApi(self.environment.api)
const result: RefreshTokenResult = yield authenticationApi.refreshToken()
if (result.kind === "ok") {
return true
} else {
__DEV__ && console.tron.log(result.kind)
return false
}
}),
}))
.actions((self) => ({
logout: flow(function* () {
const authenticationApi = new AuthenticationApi(self.environment.api)
const result: LogoutResult = yield authenticationApi.logout()
if (result.kind === "ok") {
self.setAuthenticated(false)
} else if (result.kind === "unauthorized") {
const result = yield self.refreshToken()
if (result) {
self.rootStore.authenticationStore.logout()
}
} else {
__DEV__ && console.tron.log(result.kind)
}
}),
}))
很好用,但写得不好。我应该如何改进它?不能在它下面做一些中间件吗?
以及如何为 AuthenticationApi() 类做一些依赖注入。
【问题讨论】:
标签: typescript react-native mobx mobx-state-tree