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

Power Apps组件调用自定义Action遇Xrm未定义问题求助

解决Dynamics 365中TypeScript调用自定义Action的Xrm未定义问题

问题根源

你在TypeScript组件中调用自定义Action时出现Xrm is not defined错误,核心原因是TypeScript编译阶段无法识别全局的Xrm对象——虽然浏览器运行时Xrm是全局可用的,IDE也能通过类型定义显示提示,但编译环节会抛出错误。另外Xrm.Page在新版Dynamics 365中已被弃用,不建议继续依赖。

解决方案

1. 临时解决编译报错(声明全局Xrm)

如果需要保留原有代码结构,可在TypeScript文件顶部添加全局声明,让编译器识别Xrm:

declare var Xrm: any;

但更推荐使用下面的标准方式,规避弃用API的风险。

2. 通过组件上下文获取客户端URL(推荐)

在Dynamics 365组件(如PCF组件、自定义页面组件)中,直接通过组件自带的上下文对象获取客户端URL,无需依赖Xrm.Page:

// 假设你的组件上下文为this._context(PCF组件的context示例)
const clientUrl = this._context.getClientUrl();

fetch(`${clientUrl}/api/data/v9.2/dev_GetData`, {
    method: "POST",
    headers: { 
        "Accept": "application/json",
        "Content-Type": "application/json; charset=utf-8",
        "OData-MaxVersion": "4.0",
        "OData-Version": "4.0"
    },
    body: JSON.stringify({
        "leadid": "7ba18ae0-4d0e-ea11-a813-000d3a1bbd52"
    })
}).then((response) => response.json())
.then((data) => {
    console.log(data);
})
.catch(error => {
    console.error("调用自定义Action失败:", error);
});

如果是在普通脚本(非组件)中,可改用Xrm.Utility.getGlobalContext().getClientUrl()替代弃用的Xrm.Page.context.getClientUrl()。

3. 使用Web API标准方式调用Action(更规范)

Dynamics 365 Web API提供了专门调用自定义Action的execute方法,比手动写fetch更合规,还能直接利用上下文的Web API对象:

this._context.webAPI.execute({
    boundParameter: null, // 非绑定Action填null
    entityName: null,     // 非绑定Action填null
    actionName: "dev_GetData",
    parameters: {
        "leadid": "7ba18ae0-4d0e-ea11-a813-000d3a1bbd52"
    }
}).then((response) => {
    if (response.ok) {
        return response.json();
    } else {
        throw new Error(`请求失败: ${response.statusText}`);
    }
}).then((data) => {
    console.log(data.data); // 直接获取Action的output参数data
}).catch(error => {
    console.error("调用失败:", error);
});

额外提示

确保项目中安装了Dynamics 365的TypeScript类型定义包@types/xrm,这样IDE能提供完整的类型提示,编译时也能减少报错:

npm install @types/xrm --save-dev

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:31:15