M1版MacBook Air报TypeError: cli.init is not a function如何解决
问题说明
在搭载M1芯片的MacBook Air上执行npx react-native init appName初始化React Native项目时抛出如下类型错误:
TypeError: cli.init is not a function at run (/opt/homebrew/lib/node_modules/react-native-cli/index.js:302:7) at createProject (/opt/homebrew/lib/node_modules/react-native-cli/index.js:249:3) at init (/opt/homebrew/lib/node_modules/react-native-cli/index.js:200:5) at Object.<anonymous> (/opt/homebrew/lib/node_modules/react-native-cli/index.js:153:7) at Module._compile (node:internal/modules/cjs/loader:1112:14) at Module._extensions..js (node:internal/modules/cjs/loader:1166:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:834:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) at node:internal/main/run_main_module:17:47
错误原因
该错误和M1芯片无直接关联,核心原因是本地全局安装了已经被官方废弃的旧版react-native-cli工具。旧版全局CLI的初始化逻辑和新版React Native的内置初始化逻辑不兼容,调用时找不到对应的init方法就会抛出该类型错误。
修复步骤
- 卸载全局残留的旧版
react-native-cli:
如果是通过npm全局安装的,执行:npm uninstall -g react-native-cli
如果是通过yarn全局安装的,执行:yarn global remove react-native-cli - 强制清理npm缓存,避免旧版本包残留干扰:
npm cache clean --force - 重新执行初始化命令,指定拉取最新版React Native初始化模板,避免调用到本地残留的旧CLI:
npx react-native@latest init appName
M1芯片设备执行上述命令如果遇到架构兼容报错,可以在命令前加
arch -arm64前缀指定ARM原生架构运行,命令示例:arch -arm64 npx react-native@latest init appName
- 初始化完成后进入项目目录,正常执行
npx react-native run-ios或npx react-native run-android即可启动项目。
内容的提问来源于stack exchange,提问作者Bandish Kumar
相关产品推荐
相关产品推荐

