useEffect内部的Async函数返回undefined



我有一个async函数在useEffect

useEffect(() => {
async function fetchData() {
const res = await checkLogin();
console.log(res);
}
fetchData();
}, []);

checkLogin返回"Hello world">

async function checkLogin() {
try {
const resp = await linstance.get("/api/auth/user");
setUser(resp.data.user);
setEmail(resp.data.email);
setId(resp.data.id);
return "Hello world";
} catch (error) {
return error.response;
}

}

为什么在console.log中它是print undefined?

我希望checkLogin响应为"Hello world"(为了说清楚)

checkLogin()中您的代码有try/catch。如果try block run成功,你会得到"Hello world">

但最有可能的是你的代码落入catch块。抛出错误,error对象没有response属性。在catch

catch (error) {
// check what is logging here
console.log("error in fetchLogin", error)
return error.response;
}

最新更新