I have seen the explanation of such a problem in a book on psychology. Roughly as follows: sleep is divided into four stages, and that kind of action is the second stage (fake sleep stage), that is, the dreaming stage. Every day, at night. People have the function of self-regulation, and repressed thoughts will be satisfied at this stage to adjust the balance of body and mind.