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

JavaScript中System.import嵌套调用后addMessages方法无法访问求助

解决System.import加载模块后调用addMessages失败的问题

问题根源

  • 未接收frm/mod/messages模块的导出对象,导致无法访问其内部的addMessages方法
  • 调用时方法名拼写错误:addMEssages 应为 addMessages(注意字母大小写)
  • 嵌套的System.import写法不仅低效,还容易引发作用域访问问题

解决方案

方案1:修正拼写并正确接收模块导出

先修正方法名拼写错误,同时在加载messages模块时接收其导出对象,确保方法在作用域内可访问:

System.import("frm/core").then(function(core) {
    // 接收messages模块的导出对象
    System.import("frm/mod/messages").then(function(messages) {
        core.companionScript("something", function ($element, options) {
            "use strict";

            function doSomething(password){
                // ...
                if(condition) {
                    // 通过导出对象调用正确命名的方法
                    messages.addMessages("p1", "p2", {errors : ["errKEy"]});
                }
                // ...
            }
        });
    });
});

方案2:用Promise.all并行加载模块(更优)

由于两个模块无依赖关系,无需嵌套加载,用Promise.all同时加载可提升效率,还能避免嵌套作用域问题:

Promise.all([
    System.import("frm/core"),
    System.import("frm/mod/messages")
]).then(function([core, messages]) {
    core.companionScript("something", function ($element, options) {
        "use strict";

        function doSomething(password){
            // ...
            if(condition) {
                messages.addMessages("p1", "p2", {errors : ["errKEy"]});
            }
            // ...
        }
    });
});

额外提示

如果addMessages是模块挂载到全局对象的方法,需确保模块加载完成后再调用,但这种方式不推荐——更规范的做法是通过模块导出获取方法,避免全局作用域污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:55:58