如何在.catch块中抛出SubmissionError且避免触发未处理拒绝?
Hey there, let's sort out this unhandled rejection issue you're facing with redux-form and SubmissionError.
The Root Cause
In your current code, you're directly throwing a SubmissionError inside the catch block of your fetch call. While this does reject the promise returned by your submit function, it's not being properly intercepted by redux-form's internal error handling logic, which leads to that annoying "Unhandled Rejection" warning in the browser.
The Solution
Instead of throwing the error directly, you should return a rejected promise containing the SubmissionError. This ensures redux-form catches the rejection correctly, processes the error to display form feedback, and avoids the unhandled rejection warning.
Here's the adjusted code:
import { SubmissionError } from 'redux-form'; const submit = (data) => { console.log(data); const config = { method: 'GET' }; return fetch('http://www.notAvailable.com/', config) .then(response => { console.log(response) }) .catch(err => { // Return a rejected promise with SubmissionError instead of throwing return Promise.reject(new SubmissionError({ _error: 'Error' })); }); } export default submit;
Why This Works
redux-form's submission handling expects your submit function to return a promise:
- If the promise resolves, redux-form marks the submission as successful and clears any pending states.
- If the promise rejects with a
SubmissionError, redux-form automatically maps the error details to your form's state (like showing the_errormessage at the form level) without triggering an unhandled rejection.
Throwing the error directly works in some cases, but returning Promise.reject() is more consistent and reliable across different promise implementations and redux-form versions.
内容的提问来源于stack exchange,提问作者user1885523

