react-hook-form提交失败后isSubmitting状态无法恢复问题求助
解决React Hook Form提交失败后
isSubmitting无法重置的问题 问题原因
你在异步提交函数的catch块中重新抛出异常后,这个异常如果没被handleSubmit的内置错误处理流程正确承接,会打断isSubmitting的自动重置逻辑。实际上handleSubmit内部会通过finally块在提交完成(无论成功/失败)后重置状态,但未被handleSubmit处理的异常会干扰这个流程。
解决方案
方案1:手动上报错误,不重新抛出异常
在catch块里完成错误提示和监控上报,不再抛出异常,让Promise正常结束,handleSubmit会自动重置isSubmitting:
const onSubmit = async (data) => { try { await axios.post("https://httpstat.us/500", data); } catch (err) { alert("Something went wrong"); // 直接在这里上报Sentry Sentry.captureException(err); // 移除 throw err 语句 } };
方案2:利用handleSubmit的错误回调处理上报
保留catch块中的异常抛出,同时给handleSubmit传递第二个参数(错误回调),在回调中完成监控上报。这样handleSubmit会正常捕获异常并执行状态重置:
const onSubmit = async (data) => { try { await axios.post("https://httpstat.us/500", data); } catch (err) { alert("Something went wrong"); throw err; // 将异常抛给handleSubmit的错误回调处理 } }; const handleSubmitError = (error) => { // 在这里上报Sentry Sentry.captureException(error); }; // 表单提交绑定 <form onSubmit={handleSubmit(onSubmit, handleSubmitError)}> {/* 表单字段 */} <button type="submit" disabled={isSubmitting}>Submit</button> </form>
方案3:手动维护提交状态(兜底方案,不推荐)
如果前两种方案不适用,可以自定义状态来手动控制提交状态,不过这不符合React Hook Form的设计理念,仅作为兜底:
import { useState } from 'react'; import { useForm } from 'react-hook-form'; // ... const [isFormSubmitting, setIsFormSubmitting] = useState(false); const { register, handleSubmit } = useForm(); const onSubmit = async (data) => { setIsFormSubmitting(true); try { await axios.post("https://httpstat.us/500", data); } catch (err) { alert("Something went wrong"); Sentry.captureException(err); throw err; } finally { setIsFormSubmitting(false); } }; // 按钮使用自定义状态禁用 <button type="submit" disabled={isFormSubmitting}>Submit</button>
总结
优先选择方案1或2,它们贴合React Hook Form的内置状态管理逻辑,能避免手动维护状态带来的潜在问题。
内容的提问来源于stack exchange,提问作者karthikaruna
相关产品推荐
相关产品推荐

