简体   繁体   English

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

[英]Component can't catch error from function passed as a prop

I have a Form component, and when the submit button is clicked, it calls: 我有一个Form组件,当单击Submit按钮时,它调用:

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

I'm trying to use it with onSubmit passed as: 我正在尝试通过以下方式与onSubmit一起使用它:

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

But it doesn't handle it. 但是它无法处理。 In the current version, it throws an error to the console: auth.esm.js:429 Uncaught The email address is badly formatted. 在当前版本中,它向控制台抛出错误: auth.esm.js:429 Uncaught The email address is badly formatted. I tried wrapping the error with new Error , but then it throws it to the window. 我尝试用new Error包装new Error ,但随后将其抛出到窗口中。 What am I doing wrong? 我究竟做错了什么?

A normal try/catch block cannot catch async errors. 正常的try / catch块无法捕获异步错误。 However you can declare an async block and this should work: 但是,您可以声明一个异步块,这应该可以工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 作为 prop 传入的 function 的 React 组件抛出 TypeScript 错误 - React component throwing TypeScript error for function passed in as prop 尽管组件内部调用了 to.catch,为什么 promise 没有作为道具传递 - Why isn't a promise passed as prop caught despite call to .catch inside the component 找不到屏幕“主页”的“组件”或“儿童”道具。 如果您传递了“未定义”,就会发生这种情况。 react-navigate v5 出错? - Couldn't find a 'component' or 'children' prop for the screen 'Home'. This can happen if you passed 'undefined'. Error with react-navigate v5? 无法加载通过 React App 中的父组件作为道具传递给子组件的图像 - Can't load images passed on to a child component as a prop by parent component in a React App 开玩笑如何从作为道具传递给子组件的父组件调用 function - Jest how to call a function from parent component that is passed as a prop to child component React - 使用从父组件传递的道具渲染子组件时出错 - React - Error while rendering child component with prop passed from parent component 当它作为道具传递时,如何将状态从父组件更新到子组件? - How can I update the state from parent component to child component when its passed as a prop? 在Javascript的承诺中,为什么不能将错误传递给下一个链`.catch()`? - In the Promise of Javascript, why can't the error be passed to the next chain `.catch()`? 从子组件中调用prop在函数中不起作用 - calling prop from child component in a function dosen't work 如果回调未作为道具传递,如何使用 jest 检查对子组件的点击? - How can I check a click on a child component using jest, if the callback isn't passed as prop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM