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

Ember.js控制器调用transitionToRoute提示该函数不存在问题处理

错误原因

该报错的核心是 this指向丢失:你使用普通function关键字声明的error回调会在触发时重新绑定执行上下文,此时回调内部的this不再指向原Ember Controller实例,自然无法访问Controller实例上的transitionToRoute方法。

解决方式

以下三种方案均可修复该问题:

  • 方案1:使用箭头函数绑定外层this
    箭头函数不会创建独立的执行上下文,会直接继承外层作用域的this指向,适配绝大多数ES6及以上的运行环境:
error: (jqXHR, exception) => {
  console.log('Error occured!');
  this.transitionToRoute('main');
},
  • 方案2:提前缓存Controller上下文
    如果当前环境不支持ES6语法,可以在回调外部提前存储Controller的this指向,回调内部调用缓存的上下文即可:
// 在Controller作用域内提前缓存this
const self = this;
// 其他业务逻辑
error: function (jqXHR, exception) {
  console.log('Error occured!');
  self.transitionToRoute('main');
},
  • 方案3:使用bind显式绑定上下文
    给回调函数通过bind方法显式绑定当前Controller的this指向:
error: function (jqXHR, exception) {
  console.log('Error occured!');
  this.transitionToRoute('main');
}.bind(this),

内容的提问来源于stack exchange,提问作者Aravinth K U18CA0009

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:01