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

RTK Query中使用getState获取状态报错,无法读取Store中的Token

解决Redux Toolkit Query中getState()返回unknown的类型错误

这个错误是因为TypeScript无法自动推断你的Redux根状态类型,所以getState()返回值为unknown,导致访问auth.accessToken时出现类型不兼容报错。

解决步骤:

  1. 定义根状态类型RootState
    如果还没在store配置文件里定义该类型,直接在store.ts(或你的store入口文件)中添加:

    import { configureStore } from '@reduxjs/toolkit';
    import authReducer from './features/auth/authSlice';
    import { baseApi } from './services/baseApi';
    
    export const store = configureStore({
      reducer: {
        auth: authReducer,
        [baseApi.reducerPath]: baseApi.reducer,
      },
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(baseApi.middleware),
    });
    
    // 导出根状态类型,供其他文件使用
    export type RootState = ReturnType<typeof store.getState>;
    
  2. 在baseApi中指定getState的类型
    回到你的baseApi文件,导入RootState后,给getState()的返回值显式指定类型:

    import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
    import type { RootState } from '../store'; // 路径需对应你的实际store位置
    
    export const baseApi = createApi({
      reducerPath: "baseApi",
      tagTypes: ["Todos"],
      baseQuery: fetchBaseQuery({
        baseUrl: 'http://localhost:3000/',
        prepareHeaders: (headers, { getState }) => {
          const state = getState() as RootState;
          const token = state.auth.accessToken;
          if (token) {
            headers.set('Authorization', `Bearer ${token}`);
          }
          return headers;
        },
      }),
      endpoints: () => ({}),
    });
    

也可以用更简洁的方式,给fetchBaseQuery指定泛型参数:

baseQuery: fetchBaseQuery<RootState>({
  baseUrl: 'http://localhost:3000/',
  prepareHeaders: (headers, { getState }) => {
    const token = getState().auth.accessToken;
    if (token) {
      headers.set('Authorization', `Bearer ${token}`);
    }
    return headers;
  },
}),

这样TypeScript就能正确识别状态结构,不会再报unknown类型的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:05:14