使用React Hook Form时出现Uncaught TypeError: cyclic object value错误求助
解决react-hook-form中JSON.stringify(errors)导致的"cyclic object value"错误
问题根源
react-hook-form返回的errors对象内部存在循环引用结构(比如错误对象的部分属性会引用自身或关联对象),而JSON.stringify()无法处理循环引用的对象,直接序列化会抛出Uncaught TypeError: cyclic object value错误,导致应用崩溃。
解决方案
方法1:手动提取错误关键属性
只序列化errors对象中需要的字段(如type、message),避开循环引用的部分:
function App() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { alert(JSON.stringify(data)); }; // 提取错误核心属性,避免触发循环引用 const serializedErrors = Object.fromEntries( Object.entries(errors).map(([field, err]) => [ field, { type: err.type, message: err.message } ]) ); return ( <form onSubmit={handleSubmit(onSubmit)}> <label>First Name</label> <input {...register("firstName", { required: "请输入名字", maxLength: { value: 20, message: "名字不能超过20个字符" }, pattern: { value: /^[A-Za-z]+$/i, message: "名字只能包含字母" } })} /> <pre>{JSON.stringify(serializedErrors)}</pre> <input type="submit" /> </form> ); }
方法2:遍历错误逐个展示
不依赖JSON.stringify,直接遍历errors对象渲染每个字段的错误信息,既直观又避免序列化问题:
function App() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { alert(JSON.stringify(data)); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label>First Name</label> <input {...register("firstName", { required: "请输入名字", maxLength: { value: 20, message: "名字不能超过20个字符" }, pattern: { value: /^[A-Za-z]+$/i, message: "名字只能包含字母" } })} /> {/* 遍历错误并渲染 */} {Object.entries(errors).map(([field, err]) => ( <p key={field} style={{ color: "red" }}> {err.message} </p> ))} <input type="submit" /> </form> ); }
方法3:使用支持循环引用的序列化工具
如果需要完整序列化errors对象,可以使用flatted库(专门处理循环引用的序列化):
- 安装依赖:
npm install flatted
- 替换
JSON.stringify:
import { stringify } from 'flatted'; // ... <pre>{stringify(errors)}</pre>
内容的提问来源于stack exchange,提问作者lifeisfoo
相关产品推荐
相关产品推荐

