需求:MutationObserver 的回调内部需要 await 读取环境变量,且原子化的运行(前一次变动的回调没执行完前,不会有新的回调同时运行)
只是简单地在回调里面用 await ,声明前加上 async ,显然不管用。于是尝试了下面的写法:回调里先把观察器断掉,等处理完其他事,返回前再连上。虽然写法很丑陋,且会丢掉一些变动没处理,但不影响使用场景:
let ManualHider = function(rules) { this.run = function() { this.list_observer = new MutationObserver(this.callback); this.list_observer.observe(document.querySelector(this.matching_unique_rule.root), { childList: true }); } this.callback = async function() { this.list_observer.disconnect(); // 报错的行 await new Promise(r => setTimeout(r, 3000)); // do sth asynchronously this.list_observer.observe(document.querySelector(this.matching_unique_rule.root), { childList: true }); } }; new ManualHider(rules).run(); 但是当第二次触发时,this 会变成 undefined ,提示 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'disconnect')。
这是为什么呀?另外若这种写法实在不行,还有什么简单方法(太专业的搞不来…)能实现需求吗?谢谢
(楼主文科生,偶尔代码仅自用,若说的不对,请大佬对业余者宽容谅解)
