How to use setAttributes outside of the edit function return

I am a little late on this, but for anyone searching similar answer – in first example, I would say you did not define cwraggDataSource attribute properly (you did not provide block definition code). When attribute is not defined properly, it is initialized to undefined.

As for the second example, you were trying to call setAttributes in event function, and in it setAttributes is out of scope.