Intellij+create-react-app中axios is undefined错误求助
解决「Uncaught (in promise) TypeError: axios is undefined」错误
问题根源
你代码里同时混用了ES模块的import和CommonJS的require,且在changeHandler函数内部重新声明了axios变量,引发两个核心问题:
- 顶部的
import axios from 'axios'被函数内的同名变量覆盖,IDE因此提示“未使用导入” - 函数内的
require('axios').default在ES模块环境下可能无法正确加载axios实例,导致axios变量为undefined
修复步骤
- 移除函数内的重复axios声明
删除changeHandler里的const axios = require('axios').default;,直接使用顶部导入的axios:import Navbar from 'react-bootstrap/Navbar'; import Form from 'react-bootstrap/Form'; import {InputGroup} from "react-bootstrap"; import axios from 'axios'; const api_key = process.env.API_KEY; const SearchInput = () => { async function changeHandler(e) { const url = 'https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value const config = { headers: { 'x-api-key': api_key } } // 用await处理异步请求,同时捕获错误 try { const response = await axios.get(url, config); // 这里处理返回的数据 console.log(response.data); } catch (error) { console.error('请求出错:', error); } } // ... 剩余组件代码 } - 简化请求配置
axios的get方法默认启用CORS且请求方法为GET,无需手动指定method: 'GET'和mode: 'cors',可直接省略这些冗余配置。 - 处理异步Promise
由于changeHandler是async函数,用try/catch包裹请求逻辑,避免出现未处理的Promise错误。
额外检查
- 确认项目环境:若
package.json里有"type": "module",则保持ES模块的import语法;若为CommonJS环境,统一改用require加载依赖 - 重新安装axios后,重启IDE和开发服务器,确保依赖加载生效
内容的提问来源于stack exchange,提问作者SamPhoenix
相关产品推荐
相关产品推荐

