You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整JS异步事件执行顺序?React Native登录函数返回undefined如何修复

问题根源

你的signIn函数虽然标记了async,但没有返回异步请求的Promise对象:

  • 你在signIn里直接调用了axios.post(),但没有把这个Promise返回,函数默认返回undefined
  • 所以SignInScreen里的.then()拿到的是立即返回的undefined,而axios请求是在后续异步完成的,才会打印密钥,这就是你看到输出顺序颠倒的原因。

修复步骤

第一步:修改authService.js的signIn函数

两种写法选一种即可:

写法1:直接返回axios Promise

import axios from "axios";

const signIn = (email, password) => {
  // 加return把axios的Promise返回出去
  return axios
    .post("http://127.0.0.1:8000/rest-auth/login/", {
      username: email,
      email: email,
      password: password,
    })
    .then((response) => {
      console.log(response.data.key);
      return response.data.key;
    })
    .catch((error) => {
      throw error; // 这里不要直接return error,要抛出才能被上层的catch捕获
    });
};

写法2:用async/await语法(更易读)

import axios from "axios";

const signIn = async (email, password) => {
  try {
    const response = await axios.post("http://127.0.0.1:8000/rest-auth/login/", {
      username: email,
      email: email,
      password: password,
    });
    console.log(response.data.key);
    return response.data.key;
  } catch (error) {
    throw error;
  }
};

第二步:可选优化SignInScreen的异步写法

你已经把signInUser标记为async,可以统一用await语法,逻辑更清晰:

const signInUser = async (values) => {
  const { email, password } = values;
  setSignInLoading(true);
  try {
    const response = await signIn(email, password);
    console.log(response);
    dispatch({
      type: "SIGN_IN",
      token: response,
    });
  } catch (e) {
    console.log(e);
  } finally {
    setSignInLoading(false);
  }
};

注意点

  • 异步函数如果要外部拿到返回结果,必须把内部的异步操作的Promise返回,或者用await等待异步操作完成后再返回结果
  • catch块里如果直接return error,上层的then会把error当成正常返回值处理,要抛出错误才能被上层catch捕获

内容的提问来源于stack exchange,提问作者user16372363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:12:01