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

Aurelia中使用Fetch提交表单后打印结果消息时报错的技术咨询

解决Aurelia结合Fetch时this.resultMessage无法赋值的问题

嘿,这个问题我太熟悉了!你遇到的Unhandled rejection TypeError: Cannot set property 'resultMessage' of undefined错误,本质是Fetch回调里的this上下文跑偏了——默认情况下,fetch().then()里的普通函数会改变this的指向,不再指向你的Aurelia视图模型(VM)实例,所以才会拿到undefined,没法给resultMessage赋值。

下面给你几种靠谱的解决方法:

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

箭头函数不会绑定自己的this,会继承外层作用域的this,刚好就是你的VM实例:

// add.js里的请求代码
submitForm() {
  const formData = new FormData(this.formElement);
  
  fetch('/api/books', {
    method: 'POST',
    body: formData
  })
  // 用箭头函数代替普通function
  .then(response => response.json())
  .then(data => {
    // 这里的this就是你的VM实例了
    this.resultMessage = "New book added";
  })
  .catch(error => {
    console.error('添加失败:', error);
    this.resultMessage = "Failed to add book";
  });
}

方法2:提前保存VM实例到变量

如果习惯用普通函数,可以先把this存到一个变量里(比如vm),回调里用这个变量代替this:

submitForm() {
  const formData = new FormData(this.formElement);
  // 先把VM实例存下来
  const vm = this;
  
  fetch('/api/books', {
    method: 'POST',
    body: formData
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    // 用vm代替this,避免上下文丢失
    vm.resultMessage = "New book added";
  })
  .catch(function(error) {
    console.error('添加失败:', error);
    vm.resultMessage = "Failed to add book";
  });
}

方法3:用bind()绑定上下文

给每个回调函数绑定this为VM实例,强制指定上下文:

submitForm() {
  const formData = new FormData(this.formElement);
  
  fetch('/api/books', {
    method: 'POST',
    body: formData
  })
  .then(function(response) {
    return response.json();
  })
  // 绑定this为当前VM实例
  .then(function(data) {
    this.resultMessage = "New book added";
  }.bind(this))
  .catch(function(error) {
    console.error('添加失败:', error);
    this.resultMessage = "Failed to add book";
  }.bind(this));
}

额外验证步骤

确保你已经做好这两点:

  1. 在VM类里初始化resultMessage属性:
// add.js
export class Add {
  // 初始化属性,避免初始绑定undefined
  resultMessage = '';
  
  // 其他代码...
}
  1. 在add.html里正确绑定该属性:
<!-- add.html -->
<form ref="formElement" submit.delegate="submitForm()">
  <!-- 表单内容 -->
  <button type="submit">添加书籍</button>
</form>

<!-- 显示结果消息 -->
<div class="result">${resultMessage}</div>

内容的提问来源于stack exchange,提问作者George P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:04:16