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

使用Axios连接React前端与Java后端时遇'then'未定义错误

解决Axios调用出现“'then' is undefined”的问题

出现这个错误的核心原因是axios.get()没有返回预期的Promise对象,大概率是Axios未正确导入或安装导致的,按以下步骤排查:

  • 确认Axios已安装
    在项目根目录运行安装命令:

    npm install axios
    # 或者使用yarn
    yarn add axios
    
  • 在组件中正确导入Axios
    确保调用Axios的组件顶部有导入语句:

    import axios from 'axios';
    

    忘记导入会导致axios变量为undefined,调用get()后自然无法找到then方法。

  • 排查命名冲突
    检查组件内是否有局部变量覆盖了axios,比如:

    // 错误示例:局部变量axios覆盖了导入的Axios
    const axios = 'some value';
    

    这种情况会导致axios.get()不是预期的API调用方法。

  • 验证Axios对象有效性
    在HelloWorldRestApiCall函数开头添加日志,确认Axios是否正常加载:

    function HelloWorldRestApiCall() {
      console.log('Axios object:', axios); // 若输出undefined,说明导入/安装有问题
      axios.get('http://localhost:8080/hello-world')
           .then((response) => successfulResponse(response))
           .catch((error) => errorResponse(error))
           .finally(() => console.log("clean-up"))
    }
    

修正后的完整示例代码(包含必要的React状态管理和错误处理):

import axios from 'axios';
import { useState } from 'react';

function HelloWorldComponent() {
  const [message, setMessage] = useState('');

  function HelloWorldRestApiCall() {
    if (!axios) {
      console.error('Axios未正确加载,请检查安装和导入');
      return;
    }
    axios.get('http://localhost:8080/hello-world')
         .then(successfulResponse)
         .catch(errorResponse)
         .finally(() => console.log("clean-up"))
  }

  function successfulResponse(response) {
    console.log(response);
    setMessage(response.data);
  }

  function errorResponse(error) {
    console.error('API调用失败:', error);
    // 可在此添加错误提示逻辑,比如setMessage('请求失败,请稍后重试')
  }

  return (
    <div>
      <button onClick={HelloWorldRestApiCall}>调用HelloWorld接口</button>
      <p>{message}</p>
    </div>
  );
}

export default HelloWorldComponent;

如果以上步骤排查后仍有问题,检查Axios版本是否过旧,尝试更新到最新稳定版:

npm update axios

内容的提问来源于stack exchange,提问作者Adwaith Manoj Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:45:56