【问题标题】:React Mobx with MST: Refresh token implement logicReact Mobx 与 MST:刷新令牌实现逻辑
【发布时间】:2026-01-31 12:25:02
【问题描述】:

我来自 Redux,开始学习 MST。

我尝试专业地介绍一下Token的刷新逻辑。我已经解释了它应该做什么:

  1. 客户端向服务器发送请求
  2. 服务器每 60 秒回复一次代码 401
  3. 客户端知道是401的时候要刷新token,发送刷新token请求
  4. 客户端在收到服务器的肯定响应后,是要先重复该动作。

为了整改,我使用 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


    【解决方案1】:

    我是 Ignite 和 MobX-State-Tree 的维护者。

    我建议将此重试逻辑放入您的 AuthenticationApi 类,而不是 MST 模型中。您也许可以直接使用 Axios 来执行此操作或使用 apisauce。

    就 AuthenticationApi 类的依赖注入而言,您的代码看起来不错。只需在此处注入您需要的任何东西:

    const authenticationApi = new AuthenticationApi(self.environment.api, otherDeps, etc)
    

    【讨论】: