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

在PouchDB回调中调用服务出现TypeError:无法设置undefined的itemsList

解决Angular/Ionic中PouchDB回调里Cannot set property 'itemsList' of undefined的问题

嘿,这个问题我太熟了——核心就是回调函数里的this指向不对!你在db.allDocs里用了普通的function作为回调,这时候this已经不再指向你的ContactListsPage组件实例了,自然找不到itemsList和commonServiceProvider这些组件属性。

给你两种简单靠谱的解决办法:

方法1:改用箭头函数(推荐)

箭头函数不会创建自己的this上下文,它会直接继承外层(也就是组件类)的this,完美适配这种场景:

修改后的ionViewDidLoad代码:

ionViewDidLoad() {
  this.setupDB(); //DB Setup
  // Function to check if doc exists in DB or not
  this.db.allDocs({ include_docs: true, attachments: true }, (err, response) => { // 这里改成箭头函数
    if (!err) {
      //if DB don't have any doc, call the contact service to fetch data
      if (response.total_rows == 0) {
        this.commonServiceProvider.fetchContacts()
          .subscribe((data: any) => {
            if (data.responseCode === 0) {
              this.itemsList = data.contacts;
              // Insert service data in DB
              this.db.bulkDocs(data.contacts, (err, result) => {
                if (err) {
                  console.log(err);
                }
              });
            }
          }, err => {
            console.log(err);
          });
      } else {
        this.itemsList = response.rows;
      }
    } else {
      console.log(err);
    }
  });
}

方法2:提前保存组件的this到变量

如果不想用箭头函数,也可以在回调外面把组件的this存到一个变量里(比如self),然后在回调里用self代替this:

ionViewDidLoad() {
  this.setupDB(); //DB Setup
  const self = this; // 保存组件的this到变量
  // Function to check if doc exists in DB or not
  this.db.allDocs({ include_docs: true, attachments: true }, function (err, response) {
    if (!err) {
      //if DB don't have any doc, call the contact service to fetch data
      if (response.total_rows == 0) {
        self.commonServiceProvider.fetchContacts() // 用self代替this
          .subscribe((data: any) => {
            if (data.responseCode === 0) {
              self.itemsList = data.contacts; // 这里也是self
              // Insert service data in DB
              self.db.bulkDocs(data.contacts, (err, result) => {
                if (err) {
                  console.log(err);
                }
              });
            }
          }, err => {
            console.log(err);
          });
      } else {
        self.itemsList = response.rows; // 这里同样用self
      }
    } else {
      console.log(err);
    }
  });
}

两种方法都能解决问题,个人更推荐第一种箭头函数的写法,更简洁符合现代TypeScript/Angular的编码习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:39:49