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

调用onDeviceReady时报Cannot read property 'isAvailable' of undefined错误求助

问题根源

你遇到的报错本质是this指向丢失:当你通过document.addEventListener('deviceready', this.onDeviceReady, false)注册回调时,onDeviceReady函数被触发时的this默认指向事件触发对象document,而非你的StatQuestionnaire类实例,自然读取不到挂载在类实例上的myPrinter属性,所以报错提示isAvailable的所属对象是undefined。

修复方案

方案1:用箭头函数绑定回调的this指向

将注册回调的代码修改为:

document.addEventListener('deviceready', () => this.onDeviceReady(), false);

箭头函数不会创建自己的this,会继承外层作用域的this指向,也就是printStatSite方法内的类实例this,保证onDeviceReady执行时this正确指向类实例。

方案2:用bind方法显式绑定this

也可以通过bind方法强制绑定回调的this指向:

document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);

额外问题修复

你当前代码里还有一个异步逻辑的错误:this.myPrinter.isAvailable()是异步方法,返回Promise,你现在在Promise外同步判断isAvailable的值,永远会拿到初始值true,不会等待异步判断的结果,需要把打印逻辑放到then回调内:

onDeviceReady() {
  this.browser = false;
  let options: PrintOptions = {
    name: 'Fragebogen Auswertung',
    landscape: true
  }
  // 把逻辑放到异步回调内,才能拿到正确的可用状态
  this.myPrinter.isAvailable().then((result) => {
    if(result) {
      this.myPrinter.pick();
      this.myPrinter.print(this.content, options);
    } else {
      console.log("Checks whether the device is capable of printing/Checks if the printer service is available (iOS) or if printer services are installed and enabled (Android).");
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:06:02