You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过中间件读取RTK Query返回的Action Payload

RTK Query全局错误处理:类型安全访问action payload问题

我需要通过中间件全局处理RTK Query内部异步thunk派发的action,读取其中的payload数据,但直接访问action.payload.error和action.payload.status时,因为TypeScript无法识别其类型,导致无法正常访问属性。

我的ApiSlice代码

export const ApiSlice = createApi({
    reducerPath: 'ApiSlice',

  
    baseQuery: fetchBaseQuery({
      baseUrl: Configuration.getInstance().baseURL, 
      prepareHeaders: (headers, { getState }) => {
        
        const token = (getState() as RootState).auth.token;

        if (token) {
          headers.set('authorization', `Bearer ${token}`);
        }
        return headers;
      },
    }),


    // Endpoints asignation
    endpoints: (builder) => ({
        /**
         * Login endpoint, sends a UserLoginRequest 
         * and receives an AuthResponse
         */
      login: builder.mutation<AuthInterface, UserLoginRequest>({
        query: (credentials) => ({
          url: '/login',
          method: 'POST',
          body: credentials
        }),
      }),
})

最初的错误处理中间件(类型问题)

我写的中间件里,直接访问payload的属性会因为类型未知报错:

export const errorHandlingMiddleware: Middleware =

  () => (next) => (action) => {
    

        action.payload.error // !! 无法访问,类型未知
        action.payload.status // !! 无法访问,类型未知

        Toast.show({
          type: 'error',
          text1: errorTitle,
          text2: errorStatus,
          visibilityTime: 4000,
          autoHide: true,
         });
    } 
  }
    return next(action)
  }

尝试的类型守卫方案(可行但非最优)

我用类型守卫isRejectedWithValue做了处理,虽然能运行,但感觉不是最佳方案:

export const errorHandlingMiddleware: Middleware =

  () => (next) => (action) => {
    

    if (isRejectedWithValue(action)) {
      
      console.log(action.error.code)

      let errorStatus = '';
      let errorTitle = 'Error';

      if (action.payload) {
        if (typeof action.payload === 'object') {
          if ('status' in action.payload) {
            errorStatus = action.payload.status?.toString() || errorStatus;
            errorTitle = handleErrorStatus(errorStatus);
          }
         }

        Toast.show({
          type: 'error',
          text1: errorTitle,
          text2: errorStatus,
          visibilityTime: 4000,
          autoHide: true,
         });
    } 
  }
    return next(action)
  }

我查了官方文档,但内容过时,里面的方案只用到Thunk自身的序列化错误,只会显示"Reject"消息,实用性很低。


内容的提问来源于stack exchange,提问作者Fire Frekox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:22:36