Skip to content

Writing to signals is not allowed in callbacks #49871

@peterpeterparker

Description

@peterpeterparker

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

I gave a try to Signals in v16.0.0-rc.0 and noticed that they cannot be set in callbacks which can be for example a drawback when using third party libraries.

import { Injectable, signal } from '@angular/core';

const test = (callback: (state: number) => void) => callback(1);

@Injectable({
  providedIn: 'root',
})
export class DemoService {
  private value = signal<number | undefined>(undefined);

  constructor() {
    test((state) => this.value.set(state))
  }
}

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

Lead to following error at runtime:

> in.ts:6 ERROR Error: NG0600: Writing to signals is not allowed in a `computed` or an `effect` by default. Use `allowSignalWrites` in the `CreateEffectOptions` to enable this inside effects.
>     at core.mjs:26485:15
>     at throwInvalidWriteToSignalError (core.mjs:2549:5)
>     at WritableSignalImpl.set (core.mjs:2584:13)
>     at demo.service.ts:12:32
>     at test (demo.service.ts:3:52)
>     at new DemoService (demo.service.ts:12:5)
>     at Object.DemoService_Factory [as factory] (demo.service.ts:8:25)
>     at R3Injector.hydrate (core.mjs:9162:35)
>     at R3Injector.get (core.mjs:9050:33)
>     at ChainedInjector.get (core.mjs:12850:36)
> h

Please provide the environment you discovered this bug in (run ng version)

No response

Anything else?

Angular CLI: 16.0.0-rc.0
Node: 18.15.0
Package Manager: npm 9.6.1
OS: darwin arm64

Angular: 16.0.0-rc.1
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package Version

@angular-devkit/architect 0.1600.0-rc.0
@angular-devkit/build-angular 16.0.0-rc.0
@angular-devkit/core 16.0.0-rc.0
@angular-devkit/schematics 16.0.0-rc.0
@angular/cdk 16.0.0-rc.0
@angular/cli 16.0.0-rc.0
@angular/material 16.0.0-rc.0
@schematics/angular 16.0.0-rc.0
rxjs 7.8.0
typescript 4.9.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: coreIssues related to the framework runtimebugcross-cutting: signals

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions