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

React Native报错:Cannot read property 'DocumentDir' of null求助

解决 React Native 0.71.7 中 Blob 转本地 URL 的报错问题

问题根源

rn-fetch-blob 已停止维护,对 React Native 0.70+ 版本的原生模块适配存在严重问题,导致 Cannot read property 'DocumentDir' of null 这类模块未初始化错误。转用 react-native-blob-util 后出现的 getConstants 报错,本质也是原生模块未正确链接或初始化。

分步解决步骤

1. 彻底清理旧依赖

先移除 rn-fetch-blob 避免冲突:

npm uninstall rn-fetch-blob
# yarn 用户执行
yarn remove rn-fetch-blob

清理项目缓存与原生构建文件:

npx react-native clean
cd ios && pod deintegrate && pod install && cd ..

2. 安装适配版 react-native-blob-util

选择适配 RN 0.71.x 的稳定版本:

npm install react-native-blob-util@0.17.1
# yarn 用户执行
yarn add react-native-blob-util@0.17.1

iOS 额外配置

打开 ios/Podfile,确保包含以下配置(没有则添加):

pod 'react-native-blob-util', :path => '../node_modules/react-native-blob-util'

重新执行 pod 安装:

cd ios && pod install && cd ..

Android 额外配置

检查 android/app/src/main/AndroidManifest.xml,确认添加文件读写权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android 13+ 需替换为 READ_MEDIA_VIDEO 权限。

3. Blob 转本地 URL 实现代码

使用 react-native-blob-util 的完整转换示例:

import ReactNativeBlobUtil from 'react-native-blob-util';

const convertBlobToLocalUrl = async (blob) => {
  // 获取本地文档目录
  const documentDir = ReactNativeBlobUtil.fs.dirs.DocumentDir;
  // 生成唯一文件名
  const fileName = `video_${Date.now()}.mp4`;
  const filePath = `${documentDir}/${fileName}`;

  try {
    // 将 Blob 写入本地文件(根据 Blob 实际格式调整编码,示例为 base64)
    await ReactNativeBlobUtil.fs.writeFile(filePath, blob, 'base64');
    // 返回本地文件 URL
    return `file://${filePath}`;
  } catch (error) {
    console.error('写入本地文件失败:', error);
    throw error;
  }
};

4. 排查模块初始化问题

如果仍出现 getConstants 报错:

  • 完全重启 Metro 服务、模拟器/真机
  • Android 端执行 cd android && ./gradlew clean && cd .. 后重新构建
  • iOS 端在 Xcode 中执行 Product -> Clean Build Folder 后重新编译

备选方案(上述方法无效时)

若 react-native-blob-util 仍有兼容问题,可使用 expo-file-system(裸项目也支持):

npm install expo-file-system
npx pod-install ios

转换代码示例:

import * as FileSystem from 'expo-file-system';

const convertBlobToLocalUrl = async (blob) => {
  const fileUri = `${FileSystem.documentDirectory}video_${Date.now()}.mp4`;
  // 将 Blob 转为 base64
  const base64 = await new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(blob);
  });
  // 写入本地文件
  await FileSystem.writeAsStringAsync(fileUri, base64, { encoding: FileSystem.EncodingType.Base64 });
  return fileUri;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:33:23