使用create-react-app创建Hello World时出现crypto is not a function错误
本地IP访问Create React App项目出现crypto相关错误的排查与解决
用npx create-react-app搭建了Hello World基础项目,无论通过npm start启动开发服务,还是构建后用serve运行生产版本,只要用本地IP(如192.168.1.2)访问页面就会触发错误,但用localhost或127.0.0.1访问完全正常。
触发的错误信息
第一个错误:
Uncaught (in promise) TypeError: crypto[_0xfb7f08(...)] is not a function at action ((index):1:11288) at new Promise (<anonymous>) at (index):1:11164 at _0x2f754d ((index):1:11647) at Object.get ((index):1:12733) at (index):1:46867 at _0x1daff0 ((index):1:47019) at HTMLDocument.<anonymous> ((index):1:47823)
紧接着出现第二个错误:
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
尝试过搜索相关问题,但因知识储备不足未找到有效方案,希望明确错误来源,哪怕是更换工具的解决方案也可接受。
项目依赖
"dependencies": { "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "babel-preset-es2015": "^6.24.1", "react": "^18.3.1", "react-dom": "^18.3.1", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" },
核心代码
index.js:
const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> );
App.js:
function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
错误来源分析
这个问题并非你的业务代码导致,主要有两个可能原因:
- Create React App的开发/构建流程中内置的部分脚本(比如开发环境的检测、统计类代码),在非localhost的网络上下文下,对
cryptoAPI的调用方式存在兼容性问题; - 你依赖中的
babel-preset-es2015是完全多余的——Create React App自带的Babel配置已经覆盖了ES2015及更高版本的编译需求,这个老旧的preset可能干扰默认构建流程,引发额外的兼容性异常。
解决方案
1. 移除多余依赖
先卸载无用的babel-preset-es2015:
npm uninstall babel-preset-es2015
删除package.json中对应的依赖项后,重新安装依赖:
npm install
2. 调整启动配置确保本地IP可访问
Create React App默认允许本地IP访问,但缓存可能导致异常,可尝试:
- 删除
node_modules和package-lock.json(或yarn.lock)后重新安装依赖; - 启动时显式绑定所有网络接口:
HOST=0.0.0.0 npm start
3. 更换构建工具(推荐)
Create React App已进入维护模式,官方推荐使用Vite替代,其开发和构建流程更简洁,兼容性问题更少:
- 创建Vite React项目:
npm create vite@latest my-react-app -- --template react - 进入项目目录安装依赖并启动:
Vite默认允许本地IP访问,不会出现此类crypto API相关错误。cd my-react-app npm install npm run dev
内容的提问来源于stack exchange,提问作者Brokndremes
相关产品推荐
相关产品推荐

