TypeError:无法读取未定义的属性(读取“id”)

新手上路,请多包涵

我的终端出现此错误:

TypeError:无法读取未定义的属性(读取“id”)

我正在尝试测试对 API 的调用,但出现了错误。

我的功能:

 itemToForm = () => {
    this.api.send(this.component, 'get',
        { lang: 'ES', filter: { id: this.item['id'] } }
    ).then(resEsp => {
        this.item = resEsp['data'][0];
        this.api.send(this.component, 'get',
            { lang: 'EN', filter: { id: this.item['id'] } }
        ).then(res => {
            let itemEng = res['data'][0];
            let fields = this.formDef.map(register => register.filter(
                field => field['register_table'].indexOf('traduction') !== -1
            ).map(
                field => field['field_name'])
            ).filter(register => register.length);

            fields = fields.length ? fields[0] : [];

            if (itemEng) {
                this.item = Object.keys(itemEng).reduce((obj, key) => {
                    obj[key] = this.item[key];
                    if (fields.indexOf(key) !== -1) {
                        obj[key + '_eng'] = itemEng[key];
                    }
                    return obj;
                }, {});
            }

            if (this.item) {
                this.setForm();
            }
        })
    })
}

我的规范文件:

 it('should call api.send', () => {
    let spy1 = spyOn(api, 'send');
    let item = {
        id: 1,
        name: 'test',
    }

    component.addItem(item);
    component.itemToForm();

    expect(spy1).toHaveBeenCalled();
});

原文由 David Angarita 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

怎么了:

函数 itemToForm()this.item 准备好之前被调用。

有很多策略可以避免这个错误。 一个非常简单的方法是在函数的开头添加一个捕获器,如下所示:

 itemToForm = () => {
  if(this.item === undefined) {return}

  // The rest of the code
}

如果数据尚不存在,这将停止函数。

一个更优雅的解决方案 可能是在您的操作顺序中更进一步,并找到谁在调用 itemToForm() 并确保数据在调用之前存在。

原文由 Izzi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进