控制台报Form submission canceled,handleSubmit函数未执行排查
问题分析与修复方案
核心问题:表单提交前被强制卸载
提交按钮同时绑定了type="submit"和onClick={() => setEmailSent(true)},点击按钮时onClick会优先触发,直接将emailSent设为true,组件立刻重新渲染——原来的表单被替换成“Close”按钮,导致表单还没完成提交流程就被断开,出现“Form submission canceled because the form is not connected”警告,handleSubmit自然无法执行。
修复步骤
1. 移除提交按钮的onClick事件
把状态更新逻辑移到表单提交完成后执行,避免提前卸载表单:
<button type="submit">Submit</button>
2. 在handleSubmit中完成状态更新
确保API请求成功后再切换emailSent状态,保证提交流程完整:
const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch("/api/team-members", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userId: email.userId, email: email.email }) }); const data = await response.json(); console.log(email.userId, email.email); console.log("DATA", data); // 请求完成后再更新状态 setEmailSent(true); } catch (error) { console.error("Error fetching data:", error); setEmailMessage("An error occurred while sending the invite."); } };
3. 移除handleChange中的冗余代码
input的onChange事件不需要e.preventDefault(),直接删除即可:
const handleChange = (e) => { const { name, value } = e.target; setEmail({ ...email, [name]: value }); };
完整修复后的代码
import { Fragment, useState } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import Image from 'next/image'; export default function Team({ show, setShow, userId }) { const [email, setEmail] = useState({ userId: userId, email: "" }); const [emailMessage, setEmailMessage] = useState("..."); const [emailSent, setEmailSent] = useState(false); const handleChange = (e) => { const { name, value } = e.target; setEmail({ ...email, [name]: value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch("/api/team-members", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userId: email.userId, email: email.email }) }); const data = await response.json(); console.log(email.userId, email.email); console.log("DATA", data); setEmailSent(true); } catch (error) { console.error("Error fetching data:", error); setEmailMessage("An error occurred while sending the invite."); } }; return ( <> <div > {emailSent ? ( <> <button type="button" onClick={() => setShow(false)} > Close </button> </> ) : ( <form onSubmit={handleSubmit}> <label htmlFor="email"> Member's email </label> <p>Please enter one or more emails separated by commas ','</p> <input id="email" name="email" type="email" onChange={handleChange} autoComplete="email" value={email.email} required placeholder="email@example.com" /> <button type="submit"> Submit </button> </form> )} </div> </> ) }
内容的提问来源于stack exchange,提问作者Xhris
相关产品推荐
相关产品推荐

