React Context中Async/Await返回Undefined问题求助
问题分析与修复方案
问题原因
在useApi的login方法中,处理教授登录的分支使用了.then()链式调用,但没有返回axios请求的Promise,也未用await等待请求完成。这导致该分支的异步函数执行后默认返回undefined,即便API已返回数据,AuthProvider中的data也无法接收。而学生登录分支因使用await并返回response.data,能正常获取数据。
修复后的useApi代码
将教授登录分支改为与学生分支一致的await写法,确保函数返回请求数据:
import axios from "axios"; const api = axios.create({ baseURL: process.env.REACT_APP_BASE_URL, }); export const useApi = () => ({ login: async (email: string, password: string, userType: string) => { if (userType === "professor") { const options = { method: "POST", url: `${process.env.REACT_APP_BASE_URL}/adm/admin/login`, headers: { "content-type": "application/json" }, data: { email, password, }, }; try { const response = await axios.request(options); console.log(response.data); return response.data; } catch (error) { console.error(error); throw error; // 抛出错误让上层处理 } } else if (userType === "student") { const response = await api.post("/aluno/student/login", { email, password, }); return response.data; } }, });
额外优化建议
- 统一两种登录类型的请求写法,保持代码风格一致
- 在AuthProvider的
login函数中添加错误捕获,处理登录失败场景:
const login = async (email: string, password: string, userType: string) => { try { const data = await api.login(email, password, userType); console.log(data); if (userType === "professor") { if (data?.admin && data.token) { setUser({ name: data.admin.name, email: data.admin.email, id: data.admin.id, userType: userType, }); return true; } } else if (userType === "student") { if (data?.student && data.token) { setUser({ name: data.student.name, email: data.student.email, id: data.student.id, userType: userType, }); } return true; } return false; } catch (error) { console.error("登录失败:", error); return false; } };
内容的提问来源于stack exchange,提问作者Helena Sathler
相关产品推荐
相关产品推荐

