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

社交媒体应用登录页JSON错误求助:'undefined'不是有效JSON

问题排查与修复方案

错误原因

报错'undefined' is not valid JSON的核心原因:

  • 若localStorage.getItem("user")返回字符串"undefined"(比如之前某次currentUser为undefined,执行JSON.stringify(undefined)得到undefined,存入localStorage时会被强制转为字符串"undefined"),JSON.parse("undefined")会触发JSON格式错误,因为undefined不属于合法JSON值。
  • 首次加载时若localStorage无user项,getItem返回null,JSON.parse(null)虽不会报错,但后续若currentUser变为undefined,仍会触发相同问题。

修复代码

修改初始化与存储逻辑,确保仅处理合法JSON内容:

import axios from "axios";
import { createContext, useState, useEffect } from "react";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
    // 初始化时校验存储内容有效性,避免解析错误
    const [currentUser, setCurrentUser] = useState(() => {
        const storedUser = localStorage.getItem("user");
        try {
            return storedUser ? JSON.parse(storedUser) : null;
        } catch (err) {
            // 解析失败时清空无效数据,返回默认值
            localStorage.removeItem("user");
            return null;
        }
    });

    console.log(localStorage.getItem("user"));

    const login = async (inputs) => {
        const res = await axios.post("http://localhost:8800/api/auth/login", inputs, {
            withCredentials: true,
        });
        setCurrentUser(res.data);
    };

    useEffect(() => {
        // 仅存储有效用户数据,避免存入无效值
        if (currentUser !== null && currentUser !== undefined) {
            localStorage.setItem("user", JSON.stringify(currentUser));
        } else {
            localStorage.removeItem("user");
        }
    }, [currentUser]);

    return (
        <AuthContext.Provider value={{ currentUser, login }}>
            {children}
        </AuthContext.Provider>
    );
};

额外说明

  • 补充了原代码遗漏的createContext、useState、useEffect导入。
  • 使用函数式useState初始化,避免每次渲染重复执行localStorage操作;加入try-catch捕获解析错误,防止无效存储数据导致页面崩溃。
  • 存储时校验currentUser有效性,避免存入null或undefined转换的无效字符串,同时在数据无效时移除localStorage项,保持存储清洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:45:01