NextJS中React Hook Form邮箱字段提交触发未捕获Promise错误
NextJS + React Hook Form 表单提交报错排查
问题表现
- 项目基于NextJS搭建,使用React Hook Form配合Yup做表单校验,共注册
name、email两个表单字段 - 异常触发逻辑:只要触发
onSubmit提交方法就会抛错,和email字段的校验状态完全无关:字段为空未触发校验、填写内容不符合规则校验失败、填写内容符合规则校验通过三个场景下均会复现 - 控制台报错信息:
content.js:1 Uncaught (in promise) Error: Something went wrong. Please check back shortly. at g (content.js:1:1239606)
- 业务影响:部分用户在对应设备上无法点击提交按钮
- 已做排查:参考React Hook Form官方相关issue排查未解决;测试发现唯一能消除报错的方式是移除表单标签上绑定的
onSubmit事件
现有业务代码
const confirmedGuestFormSchema = yup.object({ name: yup.string().required("To pole jest wymagane"), email: yup .string() .email("Pole musi być poprawnym adresem email") .required("To pole jest wymagane"), }); const { register, handleSubmit, formState: { errors }, reset, } = useForm<ConfirmedGuestFormData>({ resolver: yupResolver(confirmedGuestFormSchema), mode: "onBlur", }); const onSubmit = handleSubmit(async (data, e) => { console.log({ data }); // const response = await fetch("/api/send-email-to-guests", { // method: "POST", // body: JSON.stringify(data), // }); // const { message } = JSON.parse(await response.text()); // if (response.ok) { // setModalOpen(true); // setConfirmation(message); // reset(); // } }); <form className="mx-auto" onSubmit={onSubmit}> <div className="mb-5"> <label htmlFor="name" className="form-label d-none"> Imię i Nazwisko </label> <input type="text" className="form-control rounded-0 border-white bg-white-transparent" id="name" placeholder="Imię i Nazwisko" {...register("name")} /> <span className="text-xs font-thin mt-1 h-2 block text-red-600"> {errors.name?.message} </span> </div> <div className="mb-5"> <label htmlFor="email" className="form-label d-none"> Adres email </label> <input type="email" className="form-control rounded-0 border-white bg-white-transparent" id="email" placeholder="Adres email" {...register("email")} /> <span className="text-xs font-thin mt-1 h-2 block text-red-600"> {errors.email?.message} </span> </div> <div className="mb-3 form-check"> <input type="checkbox" className="form-check-input rounded-0 border-white bg-white-transparent" id="rodo" required /> </div> <button type="submit" className="btn btn-white w-100 rounded-0 text-uppercase py-3" > Potwierdzam Obecność </button> </form>;
根因定位
这个报错和你的React Hook Form、Yup业务代码完全无关,核心判断依据是报错来自content.js:这是浏览器扩展注入到页面的内容脚本,不是你项目打包生成的业务资源。
触发逻辑大概率是:出问题的设备上安装了带表单监听/自动填充功能的浏览器扩展(常见的有密码管理器、邮箱自动填充工具、广告拦截插件、购物优惠类插件),这类扩展会专门监听包含type="email"输入框的表单提交事件,当表单通过React的合成事件触发提交(也就是你绑定的onSubmit拦截了原生提交)时,扩展自身的逻辑出现bug抛出了错误;当你移除onSubmit绑定,表单走原生同步提交逻辑,扩展的监听逻辑没有命中bug,就不会报错。
验证&解决方法
- 第一步:打开浏览器无痕模式(默认会禁用所有第三方扩展),访问页面测试提交,正常情况下报错会直接消失
- 第二步:逐个禁用浏览器里安装的扩展,重点排查密码管理、自动填充、广告拦截、表单助手类扩展,定位到触发报错的扩展后,禁用/更新对应扩展即可解决
- 额外说明:你贴出的RHF、Yup代码本身写法符合规范,不存在逻辑问题;代码里的RODO复选框只加了原生
required属性但没有注册到RHF中是个小瑕疵,但不会触发这个报错。
内容的提问来源于stack exchange,提问作者seven
相关产品推荐
相关产品推荐

