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

在Next.js+Redux环境下从LocalStorage获取ID解决接口报错问题

从LocalStorage获取ID完善profileSlice服务代码

问题分析

你的代码中缺少id变量,要从LocalStorage获取用户ID,需要注意Next.js的环境差异——LocalStorage仅存在于浏览器端,直接在SSR(服务器端渲染)环境访问会报错,所以必须先做环境判断。

修改后的完整代码

import axios from "axios";
import { base_url } from "@/utils/base_url";

const getProfile = async () => {
    // 先判断是否处于浏览器环境,避免SSR报错
    if (typeof window === 'undefined') {
        throw new Error('无法在服务器端访问LocalStorage');
    }
    // 从LocalStorage读取用户ID,注意key要和存储时一致
    const userId = localStorage.getItem('user_id');
    // 校验ID是否存在,避免无效请求
    if (!userId) {
        throw new Error('未找到用户ID,请先完成登录');
    }
    const response = await axios.get(`${base_url}user/${userId}`);

    return response.data;
}

const profileService = {
    getProfile,
};
export default profileService;

关键注意事项

  • 环境判断:Next.js存在服务器端渲染场景,必须通过typeof window !== 'undefined'确保代码仅在浏览器端执行,否则会抛出window is not defined的错误。
  • 存储key一致性:localStorage.getItem('user_id')中的user_id要和你登录时存储ID用的key完全一致,比如登录成功后执行的localStorage.setItem('user_id', 当前用户ID)。
  • 错误处理:增加ID校验逻辑,避免在未登录状态下发送无效请求,同时可以在调用该服务的地方捕获错误,提示用户登录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:12:18