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

Ionic中pdfMake回调调用sendValue报错:Cannot read property 'sendValue' of undefined

问题原因分析

你遇到的这个错误核心是回调函数里的this指向不对。在getBase64的普通回调函数中,this并没有指向你的Ionic组件实例,而是指向了pdfMake内部的执行上下文,所以自然找不到组件里定义的sendValue方法。虽然console.log能正常输出pdfEncoded,但那是因为它没有依赖this的指向。

解决方案

这里有几种常用的修复方式,你可以任选一种:

1. 使用箭头函数(最推荐)

箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是你的组件实例。修改代码如下:

pdfMake.createPdf(docDefinition).getBase64((encodedString) => {
  pdfEncoded = encodedString;
  console.log(pdfEncoded);
  this.sendValue(pdfEncoded); // 现在this指向组件实例了
});

2. 提前保存组件的this到变量

在回调函数外面先把组件的this存起来,比如用that或者self:

const that = this; // 提前保存组件的this
pdfMake.createPdf(docDefinition).getBase64(function (encodedString) {
  pdfEncoded = encodedString;
  console.log(pdfEncoded);
  that.sendValue(pdfEncoded); // 用保存的that代替this
});

3. 使用bind绑定this

通过bind方法把回调函数的this强制绑定到组件实例:

pdfMake.createPdf(docDefinition).getBase64(function (encodedString) {
  pdfEncoded = encodedString;
  console.log(pdfEncoded);
  this.sendValue(pdfEncoded);
}.bind(this)); // 绑定组件的this到回调函数
验证方式

修改后再运行代码,sendValue应该就能正常接收到pdfEncoded参数了。如果还是有问题,可以先在回调里console.log(this),看看输出是不是你的组件实例,这样就能快速确认this的指向是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:18:15