You don't need to disable AsyncLocalStorage before updating the values. Rather, you should ensure that you are using als.enterWith() correctly to establish a new context with the updated values.
It is absolutely essential to exit the context properly after you've finished using it within a specific asynchronous operation. If you're entering a new context using als.enterWith(newValues), make sure you also use als.exit() when you're done with that operation to prevent memory leaks. I hope this will explain,
// Assuming this function is returning the new context with values
function createNewContextWithValues() {
const values = als.getStore()
const newValues = {
...values,
...additionalValues
}
return newValues
}
// Using the new context
async function someAsyncFunction() {
const newContext = createNewContextWithValues()
// Enter the new context with values
als.enterWith(newContext)
try {
// Your asynchronous operations that use the new context
} finally {
als.exit() // Exit the context when done, even if an error occurs
}
}
// Calling the function
someAsyncFunction()
If you are using AsyncLocalStorage in a long-running application (like a server), periodically check for any unnecessary or expired contexts and values and clean them up.