React Hook Form unregister报错:无法删除对象属性问题求助
解决react-hook-form 7.4.0嵌套字段unregister报错问题
报错原因
react-hook-form 7.4.0版本在处理嵌套对象字段的unregister操作时,内部的unset函数尝试删除对象属性,但由于表单状态对象可能被优化为不可扩展/冻结状态,导致无法删除属性抛出TypeError。
可行解决方案
方案1:升级react-hook-form版本
7.4.0是较早期的版本,后续官方修复了嵌套字段unregister的相关bug。直接升级到7.x系列的稳定版本(比如7.20+),即可解决该报错,无需修改现有逻辑。
方案2:手动清理字段值+条件校验(无需升级)
如果无法升级版本,可通过setValue清除字段值,配合条件校验替代unregister,既满足值清理需求,又能保证表单校验逻辑正常:
- 修改输入框的注册逻辑,添加条件必填校验:
{isDataEnabled && ( <Input {...register(input1Path, { required: isDataEnabled ? '此字段为必填项' : false })} /> )} {isDataEnabled && ( <Input {...register(input2Path, { required: isDataEnabled ? '此字段为必填项' : false })} /> )}
- 替换
unregister为setValue清除值+clearErrors清除校验错误:
useEffect(() => { if (!isDataEnabled ) { // 清除字段值,关闭自动校验 setValue(input1Path, undefined, { shouldValidate: false }); setValue(input2Path, undefined, { shouldValidate: false }); // 清除对应字段的校验错误 clearErrors([input1Path, input2Path]); } }, [isDataEnabled, setValue, clearErrors]);
这样处理后,当取消勾选复选框时,输入框的值会被清除,且校验规则仅在输入框显示时生效,完全符合你期望的getValues返回格式。
方案3:重置整个嵌套对象(备选)
如果允许重置整个myData对象,也可以在取消勾选时直接重置该对象,保留enabled: false即可:
useEffect(() => { if (!isDataEnabled ) { setValue(FormAttributes.MY_DATA, { enabled: false }, { shouldValidate: false }); clearErrors([input1Path, input2Path]); } }, [isDataEnabled, setValue, clearErrors]);
内容的提问来源于stack exchange,提问作者Aggat
相关产品推荐
相关产品推荐

