ngxs / store

πŸš€ NGXS - State Management for Angular
http://ngxs.io
MIT License
3.53k stars 400 forks source link

🐞[BUG]: Dispatching an Action within an `effect` causes an error #2180

Open LiamMorrow opened 1 week ago

LiamMorrow commented 1 week ago

Affected Package

ngxs/store

Is this a regression?

Yes, the previous version in which this bug was not present was: 3.8

Description

When dispatching an action which will set the state from an angular signals effect, an error now occurs saying that signals cannot be updated within an effect.

A workaround is to call the dispatch within an untracked, however the stack we get from angular is quite terrible, and having to do this for every dispatch is not a great devex.

πŸ”¬ Minimal Reproduction

https://stackblitz.com/edit/angular-17-starter-project-8ekglh?file=src%2Fmain.ts

πŸ”₯ Exception or 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.

Environment


Libs:
- @angular/core version: 17.0.0
- @ngxs/store version: 18.0.0


Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX

For Tooling issues:
- Node version: XX  
- Platform:  

Others:

markwhitfeld commented 1 week ago

@LiamMorrow Thank you for reporting this. This is definitely a bug. The source of the bug is the signal we create here: https://github.com/ngxs/store/blob/c1770480bd01ffe0592677407a17c0f64a13a8aa/packages/store/internals/src/state-stream.ts#L13-L16

It subscribes synchronously, so as soon as the state is changed, the signal is updated. I will put together a PR to resolve this.

hakimio commented 5 days ago

The error and allowSignalWrites will be removed in the near future: https://github.com/angular/angular/pull/56501

EDIT: for now might be best to use explicitEffect instead of effect().