React Native项目Axios设置Authorization头执行顺序异常问题
问题修复方案
核心问题原因
LogIn异步逻辑未正确等待:你在componentDidMount中用了await LogIn(),但LogIn函数内部的APIKit.post请求既没有加await,也没有返回对应的Promise对象,导致await没有等待登录接口返回、setClientToken执行就直接完成,提前触发了Recipe组件渲染和getRecipes请求,此时Authorization头还未赋值。setClientToken实现冗余:每次调用都新增请求拦截器的写法会导致拦截器不断累加,后续每个请求都会重复执行授权头赋值逻辑,性能和可维护性都不好。
修复步骤
1. 修正LogIn函数的异步逻辑
修改user.js中的LogIn代码,确保外层await能等待登录全流程完成:
// user.js import APIKit, { setClientToken } from "./apiKit"; export default async function LogIn(email, password) { console.log("Authenticating..."); try { // await等待登录接口返回 const token = await APIKit.post("/users/authenticate", { username: email, password: password, }) setClientToken(token) } catch (error) { console.log(error) } }
2. 优化setClientToken实现
修改APIKit.js中的setClientToken,直接修改Axios实例的全局默认请求头:
// APIKit.js export const setClientToken = (token) => { console.log("Setting token...", token.token); APIKit.defaults.headers.common["Authorization"] = `Bearer ${token.token}`; };
3. (可选)渲染时机兜底优化
如果要彻底避免异步时序导致的提前请求,可以在App组件加登录状态控制Recipe组件的渲染:
// app.js state = { isLoginCompleted: false } async componentDidMount() { console.log("Loggin in...."); await LogIn(getUser().username, getUser().password); this.setState({ isLoginCompleted: true }) console.log("Done."); } render () { // 登录完成后再渲染Recipe组件 return this.state.isLoginCompleted ? <Recipe /> : <加载状态组件 /> }
内容的提问来源于stack exchange,提问作者Malcolm S
相关产品推荐
相关产品推荐

