社交媒体应用登录页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
相关产品推荐
相关产品推荐

