From 2cfc64b3197809ccfb0a022607db8c8ecb7f053d Mon Sep 17 00:00:00 2001 From: xfy Date: Sun, 5 Jul 2026 21:59:17 +0800 Subject: [PATCH] =?UTF-8?q?fix(admin):=20SQL=20=E6=8E=A7=E5=88=B6=E5=8F=B0?= =?UTF-8?q?=20Ctrl+Enter=20=E8=A7=A6=E5=8F=91=20panic=EF=BC=88=E6=97=A0=20?= =?UTF-8?q?dioxus=20scope=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象:编辑器有焦点时点击执行(或按 Ctrl+Enter)会 panic: called `Option::unwrap()` on a `None` value (runtime.rs:223) RefCell already borrowed (runtime.rs:280) 根因:Ctrl+Enter 从 CodeMirror 的 JS 事件处理中触发 onRunShortcut 回调,此时 dioxus scope stack 为空。execute_for_editor 内部调 spawn(),而 spawn() 走 Runtime::with_current_scope → current_scope_id().unwrap(),scope stack 空时直接 panic。 第二个 panic 是 unwind 期间再次 borrow scope_stack 触发的。 修复:用 dioxus 文档推荐的 web-sys 回调模式——在组件主体捕获 scope_id(此时 scope 活跃),JS 回调里用 Runtime::current().in_scope(scope_id, ...) 重建 scope 上下文 后再执行,spawn 即可找到 origin scope。 dioxus-core 源码(global_context.rs docstring)明示此模式, dioxus-signals/src/global/mod.rs:201 也是这样用的。 注意:按钮 onclick 走 dioxus 事件系统(scope 已设),不受影响; 仅 CodeMirror JS 回调路径需要 in_scope 兜底。 --- src/pages/admin/system.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/pages/admin/system.rs b/src/pages/admin/system.rs index 24319cc..5815452 100644 --- a/src/pages/admin/system.rs +++ b/src/pages/admin/system.rs @@ -710,7 +710,7 @@ fn SqlConsoleTab() -> Element { // 用两个独立闭包(execute_for_editor / run_sql)避免 move 单一所有权冲突—— // 它们捕获相同的 Copy signal,行为完全等价。 #[cfg(target_arch = "wasm32")] - let execute_for_editor = move || { + let mut execute_for_editor = move || { running.set(true); error.set(None); let sql = sql_text.read().clone(); @@ -746,6 +746,14 @@ fn SqlConsoleTab() -> Element { }); }; + // 捕获当前 scope id:Ctrl+Enter 从 CodeMirror 的 JS 事件处理中触发时, + // dioxus scope stack 为空,spawn() 内部 current_scope_id().unwrap() 会 panic。 + // 在 effect 里用 Runtime::in_scope 重建 scope 上下文,保证 spawn 找得到 origin。 + #[cfg(target_arch = "wasm32")] + let scope_id = dioxus::core::Runtime::current() + .try_current_scope_id() + .unwrap_or(dioxus::core::ScopeId::ROOT); + // 初始化 CodeMirror + 拉取 schema 注入补全。仅 WASM。 #[cfg(target_arch = "wasm32")] { @@ -760,7 +768,12 @@ fn SqlConsoleTab() -> Element { }); let on_ready = Closure::new(|| {}); // Ctrl/Cmd+Enter 触发执行(与按钮共用同一套资源/护栏逻辑)。 - let on_run_shortcut = Closure::new(execute_for_editor); + // 从 CodeMirror JS 事件触发时无 dioxus scope,必须用 in_scope 重建。 + // execute_for_editor 是 Fn(只捕获 Copy signal),借用调用即可。 + let on_run_shortcut = Closure::new(move || { + dioxus::core::Runtime::current() + .in_scope(scope_id, || execute_for_editor()); + }); let theme_name = if resolved() == ResolvedTheme::Dark { "dark" } else { "light" }; let opts = codemirror_bridge::EditorOptions::new();