Axios响应未定义,显示控制台登录捕获



在我的登录页面中,我使用axios在单独的函数中向服务器发送响应,并使用回调来设置主login组件中的login组件状态。问题是,我得到一个Uncaught (in promise) TypeError: Cannot read property 'status' of undefined。catch中的console.log显示了TypeError: onSucceed is not a function(onSucceedStatus 200情况下的回调函数)。但我的console.log.then也显示。搞什么鬼?我的回调真的错了吗?

My Request函数:

import axios from "axios";
export const loginRequest = (state, onSucceed, onCatch) => {
axios.post("api/auth", { "email": state.email, "password": state.password })
.then((response) => {
console.log(response);
if (response.status === 200) onSucceed(response);
}).catch(exception => {
console.log(exception);
if (exception.response.status === 400) onCatch();
});
}

这是我的表单提交句柄:

const handleSubmit = (event) => {
if (state.password === "" || state.email === "") {
event.preventDefault();
setState({
...state,
emptyForm: true
})
return;
}
event.preventDefault();
loginRequest(state, props, 
(response) => {
props.loggingIn(response.data.userName, response.data.name);
setCookie({
userName: response.data.userName,
fullName: response.data.name, expireDays: 0.125, isLoggedIn: true
});
history.push("/");
},
() => {
setState({ ...state, badCredentials: true });
});

onSuccess函数在调用之前丢失了,正如错误指出的那样,这就是为什么then块抛出错误,将执行传递给catch块(其中的日志准确地显示这是错误)。至于TypeError: Cannot read property 'status' of undefined,这可能在catch块中遇到,在这里您尝试测试exception.response.status === 400的条件,exception.response可能未定义,因此尝试访问未定义的status将导致应用程序崩溃。

还注意到,在提交处理程序函数中,您使用错误的参数调用loginRequest。提供了4个参数,而不是预期的3个(state, onSuccess, onCatch)。尝试从传递给函数的参数中删除props

最新更新