dioxus icon indicating copy to clipboard operation
dioxus copied to clipboard

Trying to extract FromContext on a trait object throws a compiler error

Open techninja1008 opened this issue 9 months ago • 2 comments

Problem

The following code results in a compiler error:

use std::sync::Arc;

use dioxus::prelude::*;

trait Foo: Send + Sync {}

#[server]
pub async fn bar() -> Result<(), ServerFnError> {
    let FromContext(my_context) = extract::<FromContext<Arc<dyn Foo>>, _>().await?;
    Ok(())
}
error: higher-ranked lifetime error
  --> src/lib.rs:7:1
   |
16 | #[server]
   | ^^^^^^^^^
   |
   = note: this error originates in the attribute macro `server` (in Nightly builds, run with -Z macro-backtrace for more info)

This is because it is triggering rust-lang/rust#102211.

Steps To Reproduce

Steps to reproduce the behavior:

  1. Compile the above for server

This was a complete nightmare to track down, minimize, and fix.

Expected behavior

No compiler error, because it is valid rust code.

There are a number of ways to work around it, but the two main ones are as follows:

  1. Hide the Arc<dyn Foo> inside another type - ie. extract it into a struct. For some reason this fixes it!
  2. Make the modification below to extract (based on my limited understanding of the bug, I believe it's the explicit Send that sidesteps the issue:
pub fn extract<E: FromServerContext<I>, I>(
) -> impl std::future::Future<Output = Result<E, E::Rejection>> + Send {
    async { E::from_request(&server_context()).await }
}

Environment:

  • Dioxus version: 0.6.3
  • Rust version: tested on multiple rust versions
  • OS info: NixOS 24.11
  • App platform: N/a

Questionnaire

I would like to fix and I have a solution.

techninja1008 avatar May 19 '25 18:05 techninja1008

I have run into that rustc bug before but I haven't seen it with the extract method. It is very frustrating to debug. If the modification you posted to extract fixes the issue, that seems like a good workaround

ealmloff avatar May 19 '25 19:05 ealmloff

The key detail in the example that seems to be triggering it is the trait object - taking that out (even factoring it into a field inside a struct) gets rid of the error

techninja1008 avatar May 20 '25 14:05 techninja1008