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

React+Redux Toolkit中首次获取localStorage accessToken为空问题求助

问题原因及解决方案

问题根源

你定义的contentTypeHeaderWithToken是一个静态对象常量,当token.ts模块被加载时,localStorage.getItem('accessToken')会立即执行并赋值给Authorization字段。如果此时accessToken还没被存入localStorage(比如页面初始化时模块先加载,之后才完成登录存token),这个字段就会是空值,而且后续即使localStorage里有了token,这个静态对象的值也不会自动更新。

修复方案

把静态对象改成函数,每次发起请求时再动态获取最新的token值:

修改token.ts文件

export const getContentTypeHeaderWithToken = () => ({
  'headers': {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
  }
});

在Redux Toolkit中调用修改后的函数

export const fetchAllRoles = createAsyncThunk<IGetRolesResponse>(
  'user/getroles',
  async (user, {rejectWithValue}) => {
    try {
      // 每次请求都调用函数获取最新的请求头
      const response = await Services.get('/roles', getContentTypeHeaderWithToken());
      return response.data.slice().reverse() as IGetRolesResponse;
    } catch(err) {
      const error = err as any;
      return rejectWithValue(error?.response?.data)
    }
  },
);

这样每次执行请求时,都会重新从localStorage中读取最新的accessToken,就能避免首次执行时Authorization字段为空的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:56:03