组件无法捕获作为道具传递的函数中的错误

时间:2019-04-13 20:11:04

标签: javascript reactjs error-handling

我有一个Form组件,单击“提交”按钮时,它将调用:

//Form.js
    //...
    const submit = () => {
            try {
                onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }
    //...

我正在尝试将onSubmit用作:

export const signIn = ({ email, password }) => (
    auth()
    .signInWithEmailAndPassword(email, password)
    .catch(e => { throw e })
);

但是它无法处理。在当前版本中,它向控制台抛出错误:auth.esm.js:429 Uncaught The email address is badly formatted.我尝试用new Error包装错误,但是随后将其抛出到窗口中。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

正常的try / catch块无法捕获异步错误。但是,您可以声明一个异步块,这应该可以工作:

const submit = async () => {
            try {
                await onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }