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

React应用使用dotenv时出现Process is not defined未捕获引用错误

解决React中环境变量导致的"process is not defined"错误

问题根源

你手动引入dotenv并调用dotenv.config()的操作完全多余——现代React脚手架(如Create React App、Vite)会自动处理.env文件的加载,前端环境中不存在Node.js的process对象,因此手动调用会触发错误;同时你获取变量时写错了对象名(用了env而非正确的process.env或import.meta.env)。

具体解决步骤

  • 移除冗余的dotenv代码
    删除main.jsx中的以下两行代码:

    import dotenv from 'dotenv'
    dotenv.config()
    
  • 根据你的React脚手架类型修正变量获取方式

    • 如果你用的是Create React App(CRA):
      在component.jsx中改为:
      const api_url = process.env.REACT_APP_API_URL
      
    • 如果你用的是Vite:
      首先把.env文件里的变量名前缀改成VITE_:
      VITE_APP_API_URL="http://127.0.0.1:5000/upload"
      
      然后在component.jsx中这样获取:
      const api_url = import.meta.env.VITE_APP_API_URL
      
  • 修正.env文件格式
    变量名和值之间不要加空格,正确格式:

    REACT_APP_API_URL="http://127.0.0.1:5000/upload"
    

    (如果是Vite则用VITE_前缀的格式)

  • 重启开发服务器
    关闭当前的npm run dev进程,重新执行npm run dev,确保.env文件的修改生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:19:52