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

StencilJS更新数组报错this.documents is not iterable求助

问题根因

addNewDocument方法的this指向异常:直接将普通函数绑定到onClick事件时,函数运行时的this指向触发点击的按钮元素,而非Stencil组件实例,此时this.documents为undefined,对undefined做展开运算就会抛出「非可迭代对象」的报错。

修复方案

任选以下一种方案即可:

  • 方案1:将方法定义为箭头函数(推荐)
    箭头函数的this默认绑定定义时的组件实例,无需额外绑定:
addNewDocument = () => {
  this.documents = [...this.documents, "test2"];
}
  • 方案2:构造函数内手动绑定this
    在组件构造函数中把方法的this绑定到组件实例:
constructor() {
  super();
  this.addNewDocument = this.addNewDocument.bind(this);
}
  • 方案3:事件绑定时用箭头函数包裹
    在render方法的onClick属性中用箭头函数包裹调用,保证this指向正确:
<button onClick={() => this.addNewDocument()} type="button" class="btn btn-success">
  <i class="fa fa-plus"></i>
  <span class="btn-text">add new</span>
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:03