React集成EmailJS与reCAPTCHA后出现Uncaught (in Promise) TypeError错误求助
问题分析与解决
核心错误原因
你代码里的sendEmail函数参数定义错误——react-google-recaptcha的onChange回调只会返回验证码的响应值(captchaValue),不会传递事件对象(e)。但你当前写的是sendEmail = (e, captchaValue),这导致调用时第一个参数是验证码字符串,第二个是undefined。当执行e.preventDefault()时,因为e是字符串而非事件对象,直接触发TypeError,且错误被包裹在Promise链中,就出现了你看到的Uncaught (in Promise) TypeError。
修复步骤
- 修正
sendEmail的参数:移除多余的事件参数,仅接收captchaValue - 调整参数结构:EmailJS需要扁平的键值对参数,当前你把
formData作为嵌套对象传入,模板无法直接读取内部字段,需展开formData - 重置表单逻辑:原
e.target.reset()因无事件对象失效,改用表单ref完成重置
修改后的完整代码:
export function Form(){ const form = useRef(); const [formData, setFormData] = useState({ 'fname': '', 'lname': '', 'email': '', 'message': '', }); const[captcha, showCaptcha] = useState(false); const submitForm = (e) => { e.preventDefault(); showCaptcha(true); } const handleChange = (e) => { setFormData({...formData, [e.target.name]: e.target.value}); }; // 修正参数:仅接收验证码响应值 const sendEmail = (captchaValue) => { const params = { 'g-recaptcha-response': captchaValue, // 展开formData,转为扁平键值对 ...formData }; emailjs.send('service_id', 'template_id', params, 'public_key') .then((result) => { console.log(result.text); // 通过表单ref重置内容 form.current.reset(); // 验证完成后隐藏验证码组件 showCaptcha(false); }, (error) => { console.log(params); console.log(error); }); }; return( <> <form className="d-flex flex-column" ref={form} onSubmit={submitForm}> <label htmlFor="fname">First Name:</label> <input type="text" id="fname" name="fname" onChange={handleChange} /> <label htmlFor="lname">Last Name:</label> <input type="text" id="lname" name="lname" onChange={handleChange} /> <label htmlFor="email">Email:</label> <input type="text" id="email" name="email" onChange={handleChange} /> <label htmlFor="message">Message</label> <textarea name="message" rows="20" cols="30" onChange={handleChange} ></textarea> <fieldset className="d-flex flex-row mt-3"> <input type="submit" className="mx-2" /> <input type="reset" className="mx-2" /> </fieldset> </form> {/* 简化条件渲染逻辑 */} {captcha && ( <div className="px-3 mt-3"> <ReCAPTCHA theme='dark' sitekey='sitekey' onChange={sendEmail}/> </div> )} </> ); }
额外优化建议
- 给所有输入框绑定
value={formData.对应字段},转为标准受控组件,避免状态不一致问题 - 可在验证码验证失败时添加用户提示,提升交互体验
内容的提问来源于stack exchange,提问作者morthemex
相关产品推荐
相关产品推荐

