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

VS Code中Property 'attr' does not exist on type 'void'错误修复方案

修复Power BI视觉对象中Property 'attr' does not exist on type 'void'错误

错误原因

报错的核心问题是this.target.append("text")返回的是void类型,而非D3选择器对象,导致无法链式调用attr方法。这通常是因为:

  • this.target未被正确初始化为D3选择器(而是原生DOM元素),调用的是原生DOM的append方法而非D3的append方法;
  • 原生DOM元素的append方法返回新创建的元素,但原生元素没有attr方法,链式调用时触发类型错误。

修复步骤

1. 确保this.target正确初始化为D3选择器

在视觉对象的构造函数中,需要将options.element(Power BI提供的根DOM元素)转换为D3选择对象,必要时添加SVG容器(因为D3的文本元素需要挂载在SVG中):

constructor(options: VisualConstructorOptions) {
    // 初始化target为包含SVG的D3选择器
    this.target = d3.select(options.element)
        .append("svg")
        .attr("width", options.viewport.width)
        .attr("height", options.viewport.height);
    // 其他初始化逻辑
}

2. 修改update方法中的文本元素创建逻辑

修正链式调用,移除重复的文本设置,并在每次更新前清空旧元素避免重复渲染:

public update(options: VisualUpdateOptions) {
    // 清空之前的文本元素,防止重复创建
    this.target.selectAll("text").remove();

    // 更新SVG容器尺寸以匹配视口
    this.target
        .attr("width", options.viewport.width)
        .attr("height", options.viewport.height);

    callChatGPTAPI("Integrate Power BI with ChatGPT", "<your_openai_api_key>")
        .then(response => {
            // 链式调用D3方法创建并配置文本元素
            this.target.append("text")
                .attr("x", 10)
                .attr("y", 50)
                .attr("font-size", "14px") // 可选:添加字体样式
                .attr("fill", "#333")
                .text(response);
        })
        .catch(error => {
            console.error("Error calling ChatGPT API:", error);
        });
}

3. 额外注意事项

  • 移除原代码中重复的textElement.text(response)调用,链式调用里的text(response)已经完成文本设置;
  • 确保已正确导入D3库,项目依赖中包含d3包,且类型定义正确安装(@types/d3)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:17:32