执行bluetooth.write()时遇TypeError:无法读取undefined的bluetooth属性
解决BLE通信中TypeError: Cannot read properties of undefined (reading 'bluetooth')错误
错误原因分析
报错核心是回调函数内的this上下文丢失,导致无法访问类实例中的bluetooth属性:
onNotify回调若使用普通函数语法,this指向会绑定到回调自身而非类实例;- 回调内部使用
await但未声明为async,会进一步引发隐性逻辑问题,干扰上下文指向。
修复方案
方案1:使用async箭头函数绑定上下文
将onNotify改为async箭头函数,既保证this指向当前类实例,又支持内部的await异步操作:
修改后的问题相关代码:
this.bluetooth.startNotifying({ characteristicUUID: TIME_CORRECTION_CHARACTERISTIC_UUID, serviceUUID: SERVICE_UUID, peripheralUUID: this.stopPlatePeripheralUUID, onNotify: async (result: ReadResult) => { console.log(result); await this.bluetooth.write({ characteristicUUID: TIME_CORRECTION_CHARACTERISTIC_UUID, serviceUUID: SERVICE_UUID, peripheralUUID: this.stopPlatePeripheralUUID, value: ["ADR11BC2BEF2E9BF7530"], timeout: 10, }); }, });
方案2:提前保存上下文引用
若因环境限制无法使用箭头函数,可在调用startNotifying前保存当前实例的this引用:
const self = this; this.bluetooth.startNotifying({ characteristicUUID: TIME_CORRECTION_CHARACTERISTIC_UUID, serviceUUID: SERVICE_UUID, peripheralUUID: this.stopPlatePeripheralUUID, onNotify: async function(result: ReadResult) { console.log(result); await self.bluetooth.write({ characteristicUUID: TIME_CORRECTION_CHARACTERISTIC_UUID, serviceUUID: SERVICE_UUID, peripheralUUID: self.stopPlatePeripheralUUID, value: ["ADR11BC2BEF2E9BF7530"], timeout: 10, }); }, });
额外注意事项
- 禁止随意替换
this.bluetooth为new Bluetooth()或getBluetoothInstance():BLE通信需要复用同一个连接实例,新实例无法继承已建立的连接状态,会导致连接失效等更严重问题; - 确保
stopPlatePeripheralUUID在调用startNotifying前已正确赋值,需在设备连接完成(onConnected回调执行后)再启动通知监听逻辑。
内容的提问来源于stack exchange,提问作者RU LoN
相关产品推荐
相关产品推荐

