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

React中Axios PUT请求报错Uncaught (in promise) TypeError: Converting circular structure to JSON的问题排查与解决方案咨询

解决 Converting circular structure to JSON 错误的方案

这个错误的核心原因很明确:你的updateAPIData函数在被调用时,接收到的不是你预期的userId状态值,而是按钮点击的事件对象。事件对象内部存在循环引用(比如event.target指向DOM元素,而DOM元素又会反向引用事件),当Axios试图把请求体序列化为JSON时,就会抛出这个错误。

第一步:修复点击事件参数传递

把按钮的点击回调改成显式传递userId,而不是直接绑定函数:

// 原来的代码
<Button type='submit' onClick={updateAPIData}>Update</Button>

// 修改后的代码
<Button type='submit' onClick={() => updateAPIData(userId)}>Update</Button>

这样调用updateAPIData时,传入的就是你组件中维护的userId状态,而不是事件对象,从根源上解决循环引用的问题。

第二步:额外优化(避免其他潜在问题)

除了核心修复,还有几个细节可以优化,提升代码健壮性:

  1. 阻止表单默认提交行为
    你的按钮是type='submit',点击会触发表单的默认提交逻辑(页面刷新),这会打断Axios请求的执行。可以通过两种方式解决:

    • 把按钮类型改成button:
      <Button type='button' onClick={() => updateAPIData(userId)}>Update</Button>
      
    • 或者在回调中阻止默认行为:
      const updateAPIData = async (userId, e) => {
        e.preventDefault();
        try {
          await axios.put(`https://localhost:44373/api/Users/${userId}`, { userId, firstName, lastName, emailAddress, phoneNumber, password });
          navigate('/ReadUser');
        } catch (error) {
          console.error('更新失败:', error); // 捕获错误方便调试
        }
      }
      
      // 按钮调用时传递事件对象
      <Button type='submit' onClick={(e) => updateAPIData(userId, e)}>Update</Button>
      
  2. 修正password的初始状态
    你当前把password初始化为布尔值false,但输入框是文本类型,后续会被设置为字符串,类型不一致可能导致意外问题。改成空字符串初始化:

const [password, setPassword] = useState('');
  1. 转换userId为数字类型
    LocalStorage存储的都是字符串,而后端API期望的是整数类型的userId,在useEffect中转换类型:
useEffect(() => {
  setUserId(Number(localStorage.getItem('UserId'))); // 转成数字
  setFirstName(localStorage.getItem('First Name'));
  setLastName(localStorage.getItem('Last Name'));
  setEmailAddress(localStorage.getItem('EmailAddress'));
  setPhoneNumber(localStorage.getItem('Phonenumber'));
  setPassword(localStorage.getItem('Password'));
}, []);
  1. 添加错误捕获
    给Axios请求加上catch块,方便排查后续可能出现的API请求错误(比如后端验证失败、网络问题等)。

验证修复

完成以上修改后,Axios请求体中的所有参数都是普通的字符串/数字类型,没有循环引用,就能正常序列化为JSON发送给后端了,错误应该会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:37:36