Expo项目安装react-native-fs后触发Native module cannot be null错误如何解决
错误原因
Invariant Violation: Native module cannot be null 报错由两个核心问题共同导致:
react-native-fs依赖原生Native模块实现,你使用的标准Expo托管工作流默认不支持引入未集成到Expo SDK中的第三方原生依赖,react-native-fs不在Expo官方预置原生模块列表中,引入后无法加载对应的原生实现,直接触发空模块错误。- 业务代码中使用的相对路径
./data/user/access.json不符合React Native运行时文件读写规则,React Native不支持直接通过项目相对路径访问运行时沙箱内的文件。
修复方案
方案一:使用Expo官方文件系统模块(推荐,无需修改工作流)
无需切换Expo工作流,直接替换为Expo官方维护的 expo-file-system 模块即可:
- 卸载不兼容的
react-native-fs依赖:
npm uninstall react-native-fs # 或使用yarn yarn remove react-native-fs
- 安装官方文件系统模块:
npx expo install expo-file-system
- 替换业务代码为如下实现,路径基于Expo提供的沙箱目录拼接:
import * as FileSystem from 'expo-file-system'; ;(async ()=>{ // 拼接文件存储目录与目标文件绝对路径 const userDir = FileSystem.documentDirectory + 'data/user/'; const targetFilePath = userDir + 'access.json'; try { // 校验存储目录是否存在,不存在则递归创建 const dirStat = await FileSystem.getInfoAsync(userDir); if (!dirStat.exists) { await FileSystem.makeDirectoryAsync(userDir, { intermediates: true }); // 首次创建时初始化空数组到文件 await FileSystem.writeAsStringAsync(targetFilePath, JSON.stringify([]), { encoding: FileSystem.EncodingType.UTF8 }); } // 读取文件内容 const fileContent = await FileSystem.readAsStringAsync(targetFilePath, { encoding: FileSystem.EncodingType.UTF8 }); const dataList = JSON.parse(fileContent); // 追加数据 dataList.push({ test: 10, other: true, string: 'hello world', }); // 写入更新后的内容 await FileSystem.writeAsStringAsync(targetFilePath, JSON.stringify(dataList), { encoding: FileSystem.EncodingType.UTF8 }); } catch (err) { console.error('文件操作异常', err); } })();
修改后可直接在Expo Go中正常运行。
方案二:切换到Expo裸工作流使用react-native-fs
如果必须使用react-native-fs,需要切换到支持自定义原生模块的Expo裸工作流:
- 执行命令生成原生项目目录:
npx expo prebuild
- 进入ios目录执行
pod install完成原生模块链接 - 后续只能通过
npx expo run:android/npx expo run:ios编译运行原生项目,无法再使用Expo Go直接运行项目。
内容的提问来源于stack exchange,提问作者KAYZORK
相关产品推荐
相关产品推荐

