Vue使用web3订阅日志赋值时报非可迭代实例错误如何解决
问题解决方案
报错原因
- this指向错误:
on("data")回调使用普通函数声明,内部this指向web3订阅实例,无法访问Vue组件的this.tables属性。 - 类型不匹配:
data事件返回的log是单个对象结构,不属于可迭代的数组类型,直接使用扩展运算符...展开到数组会触发非迭代实例类型错误。
正确实现
根据业务需求选择对应写法:
场景1:将新接收的日志追加到tables数组(绝大多数业务场景适用)
改用箭头函数修正this指向,调用数组push方法或者扩展运算符追加新元素即可:
data(){ return { tables: [], subscription: null // 存储订阅实例用于后续销毁 } }, mounted(){ this.getData() }, beforeUnmount(){ // 组件销毁时取消订阅,避免内存泄漏 if(this.subscription) { this.subscription.unsubscribe() } }, methods:{ getData(){ this.subscription = web3.eth.subscribe('logs', { address: '0x123456..', topics: ['0x12345...'] }, function(error, result){ if (!error) console.log(result); }) // 箭头函数自动绑定组件this指向 .on("data", (log) => { // 写法1:push追加(Vue2/Vue3均支持响应式更新) this.tables.push(log) // 写法2:扩展运算符生成新数组赋值 // this.tables = [...this.tables, log] }) } }
场景2:将单条log对象的所有属性值转为数组存储
如果业务需要提取单条log的属性值存为数组,可以先通过Object.values()将对象转为可迭代的属性值数组再展开:
.on("data", (log) => { this.tables = [...Object.values(log)] })
内容的提问来源于stack exchange,提问作者Miles Selim
相关产品推荐
相关产品推荐

