Skip to content

Question: Lifetime safety of [&value] capture in codegen event emitter templateΒ #15685

@ericfle

Description

@ericfle

I noticed that this recent change modified the codegen event emitter lambda capture from [value] to [&value] in GenerateComponentWindows.ts (maybe to support JSValue fields?).

The generated code looks like:

void onMyEvent(OnMyEvent &value) const {
    m_eventEmitter.DispatchEvent(L"myEvent", [&value](const auto writer) {
      WriteValue(writer, value);
    });
}

The thing is now I'm experiencing crashes (access violations in winrt::to_hstring via MultiByteToWideChar) and incorrect values on the JS side when dispatching events from a custom Fabric component. The behavior seems to be consistent with value being read after the caller's stack frame is destroyed.

Looking at the dispatch chain, AbiEventEmitter::DispatchEvent passes the lambda through EventEmitter::dispatchEvent β†’ EventQueue::enqueueEvent, which suggests the lambda may execute after value goes out of scope. Facebook's core C++ event emitters (e.g., ImageEventEmitter) capture by value in their dispatch lambdas.

Do I'm missing something? Is there something in the RNW dispatch path that ensures value stays alive until the lambda executes?
What's the recommended pattern for dispatching events for example with std::string fields from custom Fabric components?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Triage πŸ”New issue that needs to be reviewed by the issue management team (label applied by bot)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions