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

NextJS Dashboard中API用户认证异步返回undefined问题求助

NextAuth认证失败:异步函数提前返回undefined的问题

你在学习NextJS Dashboard认证教程时,用自定义API替代PostgreSQL获取用户数据,但调用getUser时,函数先返回undefined,导致认证流程判定无用户,而API响应后才拿到正确用户信息,最终触发CredentialsSignin错误。

问题原因

getUser函数虽然标记为async,但内部使用axios.post().then()的回调式写法,却没有返回axios请求的Promise:

  • 函数执行到console.log("end of getUser")后就直接结束,没有等待axios请求完成,因此await getUser()会立即得到undefined
  • .then()里的return userAuthenticated只是回调函数的返回值,不会作为getUser函数的返回值传递出去

解决方案

把axios的回调写法改成async/await,确保函数等待API响应后再返回结果,同时正确处理错误情况:

修正后的getUser函数代码:

async function getUser(email: string, password: string): Promise<User | undefined> {
  const axios = require('axios');
  try {
    const response = await axios.post(`http://localhost:4000/v1/auth/`, { email, password });
    console.log("response.data.user:", response.data.user);
    const userAuthenticated: User = {
      id: response.data.user.id,
      name: `${response.data.user.first_name} ${response.data.user.last_name}`,
      email: response.data.user.email,
      password: ''
    };
    console.log("return userAuthenticated", userAuthenticated);
    return userAuthenticated;
  } catch (error: any) {
    console.log("error:", error.response?.data?.error);
    return undefined; // 请求失败时返回undefined,让认证流程判定无用户
  }
}

额外优化建议

  • 把const axios = require('axios');移到文件顶部,改成ES模块导入:import axios from 'axios';,符合NextJS的模块规范
  • 错误处理中可以根据API返回的错误信息,输出更详细内容方便调试

修正后日志顺序会变为:

  1. 发送API请求并等待响应
  2. 打印response.data.user和return userAuthenticated
  3. 打印end of getUser
  4. await getUser: 拿到正确的用户对象
  5. 执行console.log('user:', user),返回用户完成认证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:37:22