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

点击D3饼图扇区触发this.set() is not a function错误求助

解决D3点击事件中this.set() is not a function的问题

这个问题的核心是作用域混淆:在D3的事件回调函数里,this指向的是被点击的DOM元素(也就是你的饼图扇区),而不是你的Ember组件实例——这就是为什么你在组件其他地方能正常用this.get()/this.set(),但在点击回调里不行的原因。

几种可行的解决方案:

1. 提前保存组件的this引用

在绑定事件之前,把组件的this存到一个变量里,在回调中使用这个变量来调用set():

// 先保存组件实例的引用
const component = this;

let g = svg.selectAll("arc")
 .data(mpie)
 .enter().append("g")
 .attr("class", "arc")

g
 .on("mousemove", function(d) {
 var mouseVal = mouse(this);
 div
 .html("Items: " + d.data.count + "</br>" + "Date: " + d.data.label)
 .style("left", (event.pageX + 12) + "px")
 .style("top", (event.pageY - 10) + "px")
 .style("opacity", 1)
 .style("display", "block");
 })
 .on("mouseout", function() {
 div.html(" ").style("display", "none");
 })
 .on("click", function(d) {
   // 使用提前保存的组件实例调用set
   component.set('selectedLabel', d.data.label);
 })

2. 使用箭头函数绑定外部作用域的this

箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的组件实例),这样就能直接在回调里用this.set()了:

let g = svg.selectAll("arc")
 .data(mpie)
 .enter().append("g")
 .attr("class", "arc")

g
 .on("mousemove", function(d) {
 var mouseVal = mouse(this);
 div
 .html("Items: " + d.data.count + "</br>" + "Date: " + d.data.label)
 .style("left", (event.pageX + 12) + "px")
 .style("top", (event.pageY - 10) + "px")
 .style("opacity", 1)
 .style("display", "block");
 })
 .on("mouseout", function() {
 div.html(" ").style("display", "none");
 })
 .on("click", (d) => {
   // 箭头函数的this就是组件实例
   this.set('selectedLabel', d.data.label);
 })

3. 正确使用Ember.set()

如果你想用Ember.set(),要确保第一个参数是组件实例,而不是DOM元素。结合第一种方法的变量保存,写法如下:

const component = this;

// ... 其他代码

.on("click", function(d) {
  Ember.set(component, 'selectedLabel', d.data.label);
})

你之前调用Ember.set()返回空值错误,大概率是把回调里的this(DOM元素)传进去了,而不是组件实例,所以才会出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:13:49