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

处理POST请求体时遇TypeError:无法添加属性,对象不可扩展

解决"Cannot add property identity, object is not extensible"错误

错误原因

你用{ ...values.customerCase}做的是浅拷贝,只会复制外层对象的属性,内部的prepareBody.case仍然引用着原对象的引用。如果原values.customerCase.case被标记为不可扩展(比如通过Object.preventExtensions()、Object.freeze(),或是来自Redux等状态管理库的不可变对象),就无法给它添加新的identity属性,也不能修改现有属性。

修复方案

方案1:深度拷贝整个对象

通过深度拷贝把嵌套对象也复制为新的可扩展对象,适合纯数据对象(无函数、undefined等特殊值)的场景:

const handleSubmit = (values: any, formikHelpers: FormikHelpers<any>) => {
    // 深度拷贝生成完全独立的可扩展对象
    const prepareBody = JSON.parse(JSON.stringify(values.customerCase));
    if (type === '1') {
      prepareBody.case.identity = {
        title: values.customerCase.customer.contact.title,
        firstName: values.customerCase.customer.contact.firstName,
        lastName: values.customerCase.customer.contact.lastName
      };
      prepareBody.case.type = type;
    }
    PostCustomer({
      reference: props.reference,
      body: prepareBody,
    })
      .unwrap()
      .then(() => {
        formikHelpers.resetForm();
        history.push('/success');
      })
      .catch(() => alertToasts('error', t('toast.error')));
};

方案2:手动重构嵌套的case对象

如果不想用深度拷贝,可以重新创建case对象,继承原有属性后再添加新属性,可控性更强:

const handleSubmit = (values: any, formikHelpers: FormikHelpers<any>) => {
    const prepareBody = { ...values.customerCase};
    if (type === '1') {
      // 重新构建case对象,保留原有属性的同时添加新内容
      prepareBody.case = {
        ...prepareBody.case,
        type: type,
        identity: {
          title: values.customerCase.customer.contact.title,
          firstName: values.customerCase.customer.contact.firstName,
          lastName: values.customerCase.customer.contact.lastName
        }
      };
    }
    PostCustomer({
      reference: props.reference,
      body: prepareBody,
    })
      .unwrap()
      .then(() => {
        formikHelpers.resetForm();
        history.push('/success');
      })
      .catch(() => alertToasts('error', t('toast.error')));
};

补充说明

如果原对象来自第三方库或状态管理的不可变数据结构,优先选择方案2,避免深度拷贝可能丢失特殊类型数据的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:40:17