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

React函数运行报Uncaught TypeError: JSON.parse(...) is null错误怎么解决?

报错原因

核心触发场景是用户首次访问页面时,本地存储不存在cart键对应的数据:
localStorage.getItem("cart")找不到对应值时会返回null,JSON.parse(null)执行结果仍为null,对null调用数组方法push()就会抛出你遇到的类型错误。

修复代码

给购物车变量加空数组兜底默认值即可解决,同时删除冗余的无效变量声明,优化后代码如下:

addItem = () => {
  // 读取本地存储的购物车数据,不存在则初始化为空数组
  let cart = [];
  const storedCart = localStorage.getItem("cart");
  if (storedCart) {
    try {
      cart = JSON.parse(storedCart);
    } catch (err) {
      // 本地存储数据异常时兜底重置为空数组
      cart = [];
    }
  }
  // 非空判断避免写入空内容
  if (this.state.input) {
    cart.push(this.state.input);
  }
  this.setState({ cart });
  localStorage.setItem("cart", JSON.stringify(cart));
};

如果不需要兼容本地存储被篡改的异常数据场景,可以用简化写法:

addItem = () => {
  const cart = JSON.parse(localStorage.getItem("cart") || "[]");
  cart.push(this.state.input);
  this.setState({ cart });
  localStorage.setItem("cart", JSON.stringify(cart));
};

额外说明

你原有代码第一行var cart = this.state.cart;属于无效代码,下一行直接从本地存储取值覆盖了该变量,没有实际作用可直接删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:06:02