JavaScript:无法捕获异步函数中的错误
JavaScript:无法捕获异步函数中的错误,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,handleEmailSubmit函数不会捕获任何错误,即使loginWithEmail函数抛出错误。 可能是我对异步函数缺乏理解。 我需要你的帮助。多谢各位 Login.tsx const Login: React.FC = () => { const [errorMsg, setErrorMsg] = useState<string>(''); const history = useHistory(); const handleEmailSubmit = us
handleEmailSubmit
函数不会捕获任何错误,即使loginWithEmail
函数抛出错误。
可能是我对异步函数缺乏理解。
我需要你的帮助。多谢各位
Login.tsx
const Login: React.FC = () => {
const [errorMsg, setErrorMsg] = useState<string>('');
const history = useHistory();
const handleEmailSubmit = useCallback(async (e) => {
e.preventDefault();
const { email, password } = e.target.elements;
loginWithEmail(email.value, password.value)
.then(() => {
history.push('/');
})
.catch((error) => {
// this block isn't called!
setErrorMsg(error.message);
});
}, []);
return (
<>
<h2>Login</h2>
<form onSubmit={handleEmailSubmit}>
<InputGroup>
<label htmlFor="email">Email</label>
<TextField
id="email"
name="email"
type="email"
/>
</InputGroup>
<InputGroup>
<label htmlFor="password">Password</label>
<TextField
id="password"
name="password"
type="password"
/>
</InputGroup>
<Button type="submit">
送信する
</Button>
</form>
</>
);
}
您需要在catch语句中抛出错误
app
.auth()
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
userCredential.user?.getIdToken(true).then((token: string) => {
axios
.get('https://dev.myserver.com/api/v1/users/auth', {
headers: { Authorization: `Bearer ${token}` },
})
.catch((error) => {
app.auth().signOut();
throw error;
});
});
})
.catch((error) => {
console.log(error);
throw error; // there could be something wrong here
});
您是否缺少
wait
?您不返回axios.get()调用。所以,你永远不会得到它可能抛出的任何错误。@francojay抱歉,我应该在这段代码上使用await
到哪里?你既不返回用app
创建的链所创建的承诺,也不在loginWithEmail
中有await
,由于您违反了承诺链,错误无法传播。@t.niese谢谢您的建议!现在我明白为什么我的代码不起作用了!我将wait
添加到loginWithEmail
功能中。感谢您的回答,但这不起作用:(
app
.auth()
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
userCredential.user?.getIdToken(true).then((token: string) => {
axios
.get('https://dev.myserver.com/api/v1/users/auth', {
headers: { Authorization: `Bearer ${token}` },
})
.catch((error) => {
app.auth().signOut();
throw error;
});
});
})
.catch((error) => {
console.log(error);
throw error; // there could be something wrong here
});