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

React Native使用react-native-ble-plx报错:Cannot read property 'createClient' of null

解决react-native-ble-plx在Expo Go中初始化报错的问题

问题原因

react-native-ble-plx是依赖原生代码的第三方库,而Expo Go是预编译的通用客户端,不包含该库的原生实现,导致初始化BleManager时无法找到对应的原生方法,抛出Cannot read property 'createClient' of null错误。

解决方案

方案1:改用Expo官方支持的BLE库(推荐)

使用expo-ble,这是Expo官方维护的BLE库,无需处理原生配置,直接兼容Expo Go:

  1. 安装依赖:
npx expo install expo-ble
  1. 替换原有代码示例:
import * as BleManager from 'expo-ble';

// 请求蓝牙权限
async function requestPermissions() {
  const { status } = await BleManager.requestPermissionsAsync();
  if (status !== 'granted') {
    alert('需要蓝牙权限才能使用');
    return;
  }
}

// 扫描BLE设备
async function scanDevices() {
  await requestPermissions();
  const subscription = BleManager.startDeviceScan(null, null, (error, device) => {
    if (error) {
      console.error(error);
      return;
    }
    console.log('发现设备:', device.name, device.id);
    // 找到目标设备后停止扫描
    if (device.name === 'ESP32_DEVICE') {
      BleManager.stopDeviceScan();
      // 后续连接逻辑
    }
  });
}

方案2:继续使用react-native-ble-plx(需构建自定义开发客户端)

如果必须使用react-native-ble-plx,需要创建Expo开发构建,将库的原生代码打包到客户端中:

  1. 安装开发客户端依赖:
npx expo install expo-dev-client
  1. 安装react-native-ble-plx(如果还没装):
npm install react-native-ble-plx@^3.1.2
  1. 构建Android开发客户端:
npx expo run:android
  1. 构建完成后,使用生成的自定义客户端(而非Expo Go)运行项目,此时BleManager初始化即可正常工作。

额外注意事项

  • Android平台需要配置蓝牙相关权限,在app.json的expo.android.permissions中添加:
"permissions": [
  "android.permission.BLUETOOTH_SCAN",
  "android.permission.BLUETOOTH_CONNECT",
  "android.permission.ACCESS_FINE_LOCATION"
]
  • 测试前确保手机蓝牙已开启,部分Android版本需要开启定位才能扫描BLE设备。

内容的提问来源于stack exchange,提问作者Taboka Fanuel Sialumba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:10:14